Performance: setTimeout and clearTimeout
This concept affects how delayed tasks impact event loop responsiveness and CPU usage in Node.js applications.
Jump into concepts and practice - no test required
const timer = setTimeout(() => {
console.log('Task executed');
}, 10000);
// Cancel timer if task is no longer needed
clearTimeout(timer);const timer = setTimeout(() => {
console.log('Task executed');
}, 10000);
// No clearTimeout called even if task no longer needed| Pattern | Event Loop Impact | CPU Usage | Responsiveness | Verdict |
|---|---|---|---|---|
| setTimeout without clearTimeout | Schedules callback even if unused | Higher due to unnecessary callback | Lower due to event loop delay | [X] Bad |
| setTimeout with clearTimeout | Cancels unused callback | Lower CPU usage | Higher responsiveness | [OK] Good |
setTimeout function do in Node.js?setTimeout schedules a function to run once after a delay in milliseconds.setInterval, the option about stopping a running function immediately is incorrect, and the option about scheduling when the program ends is incorrect.setTimeout?clearTimeout with the timeout ID.clearTimeout(timeoutId); uses the correct function name. cancelTimeout and stopTimeout do not exist. clearInterval(timeoutId); is for intervals, not timeouts.const id = setTimeout(() => console.log('Hello'), 1000);
clearTimeout(id);
console.log('Done');clearTimeout(id).console.log('Done') runs immediately, so only 'Done' is printed.const timer = setTimeout(() => console.log('Run'), 2000);
clearTimeout(timer);
clearTimeout(timer);clearTimeout multiple times on the same ID does not cause errors; it safely ignores subsequent calls.console.log('Start');
const id = setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
clearTimeout(id);
console.log('Cancelled');
};
B) console.log('Start');
setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
clearTimeout();
console.log('Cancelled');
};
C) console.log('Start');
const id = setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
console.log('Cancelled');
clearTimeout();
};
D) console.log('Start');
const id = setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
clearInterval(id);
console.log('Cancelled');
};clearTimeout() without an argument (no effect). The third option stores the ID but calls clearTimeout() without passing the ID (no effect). The fourth option uses clearInterval(id), which cannot cancel a timeout.