Sub topic 6
What setTimeout(fn, 0) Really Means
This chapter assumes you know the call stack, host APIs, the task queue, and how one turn of the event loop picks a task. With that model, setTimeout is easy to reason about: it asks the host to queue a task later. The delay you pass sets the earliest time that task can join the queue. It never promises when the callback will run.
The Delay Is a Minimum
When you call setTimeout(fn, ms), the host starts a timer outside the JavaScript thread. When the timer expires, the host puts fn in the task queue. The event loop can only take that task once the call stack is empty. Tasks queued ahead of it also run first.
const start = Date.now();
setTimeout(() => {
console.log('timer ran after', Date.now() - start, 'ms');
}, 0);
// Busy-wait for about 200 ms, blocking the thread
while (Date.now() - start < 200) {}
// The timer callback logs roughly 200 ms, not 0 msThe timer expires almost immediately, but its task sits in the queue until the while loop finishes. So setTimeout(fn, 0) means "run fn as a new task, after the current code and anything already queued." It does not mean "run fn now."
Clamping and Throttling
The real delay can be longer than you asked for, even when the thread is idle:
| Situation | Effect |
|---|---|
| Node.js, delay of `0` | Treated as 1 ms |
| Browser, timers nested more than 5 levels deep | Minimum delay of 4 ms |
| Browser tab in the background | Often throttled to about 1 s or more |
| Negative or non-numeric delay | Treated as 0 |
Timers with equal delays that are scheduled in order fire in that order. A shorter delay scheduled later can still fire first:
setTimeout(() => console.log('slow'), 10);
setTimeout(() => console.log('fast'), 0);
setTimeout(() => console.log('fast 2'), 0);
// Output: fast, fast 2, slowsetInterval Does Not Keep Perfect Time
setInterval(fn, ms) asks the host to queue fn again every ms milliseconds. When a callback takes longer than the interval, hosts do not stack up the missed runs. The next run happens as soon as possible, so the gaps between runs shrink or drift. If you need a guaranteed pause between runs, chain timeouts instead:
let count = 0;
function tick() {
count++;
console.log('tick', count);
if (count < 3) {
setTimeout(tick, 100); // next run is scheduled after this one finishes
}
}
setTimeout(tick, 100);Common Errors
- Expecting
setTimeout(fn, 0)to run before promise callbacks. Timers are tasks, and the next chapter shows that microtasks run first. - Using a timer delay to "wait for" another async operation. Chain on that operation's completion instead.
- Forgetting
clearTimeoutorclearInterval, which leaves callbacks firing after a component or request is gone.
Exercise
A script calls setTimeout(fn, 50), then runs synchronous code that takes 120 ms. Roughly when does fn run, and why?
Show answer
At about 120 ms. The timer expires at 50 ms and queues fn, but the event loop cannot take that task until the synchronous code finishes and the call stack is empty.
Exercise
A setInterval callback with a 100 ms interval sometimes takes 150 ms to run. How would you guarantee at least 100 ms of idle time between runs?
Show answer
Replace setInterval with a setTimeout that the callback schedules again at its end, for example setTimeout(tick, 100) as the last line of tick. Each wait then starts only after the previous run has finished.