Performance: Recursive setTimeout vs setInterval
This concept affects how timers impact event loop responsiveness and CPU usage in Node.js applications.
Jump into concepts and practice - no test required
function recursiveTimeout() {
// task code
setTimeout(recursiveTimeout, 1000);
}
recursiveTimeout();setInterval(() => {
// task code
}, 1000);| Pattern | Event Loop Impact | Overlap Risk | CPU Usage | Verdict |
|---|---|---|---|---|
| setInterval | Queues callbacks every interval | High if task > interval | Spikes due to overlap | [X] Bad |
| Recursive setTimeout | Queues next callback after task | None | Smooth, controlled | [OK] Good |
setInterval and recursive setTimeout in Node.js?setInterval behaviorsetInterval schedules a function to run repeatedly at fixed time intervals without waiting for the previous run to finish.setTimeout behaviorsetTimeout schedules the next run only after the current function completes, avoiding overlap.setInterval runs tasks at fixed intervals regardless of task duration, recursive setTimeout waits for the task to finish before scheduling the next. -> Option BsetTimeout that logs "Hello" every 2 seconds?setTimeout patternsetTimeout inside itself after logging, ensuring repeated delayed calls.setTimeout, then starts it by calling repeat().let count = 0;
function tick() {
console.log(count);
count++;
if (count < 3) {
setTimeout(tick, 1000);
}
}
tick();
What will be the output and timing behavior?setTimeout callstick logs count, increments it, and schedules next call after 1 second if count < 3.setTimeout:
function repeat() {
setTimeout(() => {
console.log('Tick');
}, 1000);
repeat();
}
repeat();repeat calls itself immediately after scheduling setTimeout, without waiting for the timeout to finish.setIntervalsetInterval runs tasks at fixed intervals regardless of task duration, causing overlap if task takes longer than interval.setTimeout to control timingsetTimeout schedules the next run only after the current task finishes, preventing overlap.setTimeout scheduling the next call only after task finishes. -> Option A