Sub topic 6
What setTimeout(fn, 0) Really Means
This chapter assumes you know the earlier material in the tutorial: JavaScript runs on one thread, functions run on the call stack, host APIs do the waiting, and the event loop takes one task at a time from the task queue. You should also be comfortable with callbacks and with running code in a browser console or in Node.js.
setTimeout(fn, 0) looks like "run fn now." It actually means "queue fn as a task once at least 0 ms have passed, and run it when the event loop gets to it." This chapter explains what the delay controls, what it does not control, and the rules browsers and Node.js add on top.
The Delay Is a Minimum
When you call setTimeout(fn, delay), the engine does not start a countdown on the JavaScript thread. It passes the timer to the host, which is the browser or Node.js. The host waits in the background. When the delay has elapsed, the host puts a task for fn into a queue. From then on, fn is an ordinary task. It runs only after the current task finishes, the call stack is empty, the microtask queue has been drained, and the event loop picks it.
The delay therefore sets the earliest time the callback can become eligible to run. It does not promise when the callback will run.
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 and its task sits in the queue. The while loop keeps the call stack busy for 200 ms, so the event loop cannot start the next task. The callback runs only after the script's own task ends.
Why Zero Is Still Later Than a Promise
Promise callbacks are microtasks, and timers are tasks. The event loop drains every microtask before it starts the next task, so a resolved promise's .then callback always runs before a zero-delay timer that was scheduled in the same task:
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('sync');
// Output: sync, promise, timeoutMicrotasks get their own chapter. For timers, the point is that setTimeout(fn, 0) sends fn to the back of the task line. It runs no earlier than the next turn of the loop.
How Hosts Adjust the Delay
Hosts do not use the number you pass exactly as written. Before scheduling, they normalize it.
| Input or situation | Browser behavior | Node.js behavior |
|---|---|---|
| Omitted, negative, or `NaN` | Treated as 0 | Treated as 1 ms |
| `0` | 0 at first, clamped to 4 ms when deeply nested | Treated as 1 ms |
| Non-number such as `'100'` | Converted to a number (100) | Converted to a number (100) |
| Greater than 2147483647 (about 24.8 days) | Overflows and fires almost immediately | Set to 1 ms with a `TimeoutOverflowWarning` |
| Page in a background tab | Often throttled to at least 1 s, sometimes more | Not applicable |
The 4 ms Nesting Clamp
The HTML specification tracks a nesting level for timers. A timer scheduled from inside another timer's callback has a nesting level one higher than its parent. Once the nesting level goes past 5, any delay under 4 ms is raised to 4 ms. This keeps pages from busy-looping through timers that reschedule themselves at full speed.
You can see it by measuring the gaps:
let last = performance.now();
let level = 0;
function tick() {
const now = performance.now();
console.log(`level ${level}: ${(now - last).toFixed(2)} ms`);
last = now;
if (++level < 10) {
setTimeout(tick, 0);
}
}
setTimeout(tick, 0);In a browser console, the first few gaps are usually well under 1 ms. The later gaps settle at about 4 ms or more. In Node.js, which does not use the HTML clamp, every gap stays near 1 ms.
Background Throttling
Browsers throttle timers in tabs the user cannot see, to save battery and CPU. A 100 ms interval in a hidden tab might fire once a second, and some browsers throttle long-hidden pages even harder. Don't use timers to measure elapsed time. Read Date.now() or performance.now() when the callback runs and compute the real gap.
Ordering Among Timers
Timers that expire at the same time run in the order they were scheduled. A timer with a shorter delay usually runs before one with a longer delay, but nothing guarantees this when delays are close and the thread is busy. Here is the reliable case:
setTimeout(() => console.log('first'), 0);
setTimeout(() => console.log('second'), 0);
setTimeout(() => console.log('third'), 10);
// Output: first, second, thirdEach callback is its own task. Microtasks queued inside first run before second starts:
setTimeout(() => {
console.log('timer 1');
Promise.resolve().then(() => console.log('microtask from timer 1'));
}, 0);
setTimeout(() => console.log('timer 2'), 0);
// Output: timer 1, microtask from timer 1, timer 2This works in current browsers and in Node.js 11 and later. Node.js versions before 11 ran all expired timers before draining microtasks, which printed timer 2 before the microtask.
setInterval and Its Drift
setInterval(fn, ms) schedules fn repeatedly. It suffers from the same delays as a timeout, plus one more: it ignores how long fn takes. If the callback takes 40 ms on a 50 ms interval, only 10 ms of idle time remain between runs. If the thread is blocked through several intervals, the host does not queue a backlog of runs. It skips the missed runs and fires once when it can.
When each run must finish before the next one is scheduled, use a recursive setTimeout:
let count = 0;
function poll() {
count++;
console.log('poll', count, 'at', Date.now());
// Simulated work would go here
if (count < 5) {
setTimeout(poll, 100); // schedule the next run after this one ends
}
}
setTimeout(poll, 100);With this pattern the 100 ms gap is measured from the end of one run to the start of the next. Runs never overlap and never pile up. This matters when the work is itself asynchronous, such as a network request that might take longer than the interval.
Passing Arguments and `this`
Any arguments after the delay are passed to the callback:
function greet(name, punctuation) {
console.log(`Hello, ${name}${punctuation}`);
}
setTimeout(greet, 0, 'Ada', '!');
// Output: Hello, Ada!The callback runs as a plain function call, so a method passed as setTimeout(obj.method, 0) loses its this. Wrap it with () => obj.method() or use obj.method.bind(obj).
Common Errors
- Using
setTimeout(fn, 0)to "wait for the DOM to update." The timer does run after the current task. Whether the browser has rendered by then is not guaranteed. The rendering chapter coversrequestAnimationFrame, which is designed for that job. - Assuming
setTimeout(fn, 0)runs before a promise callback. It never does when both are scheduled from the same task. - Treating timers as clocks. Clamping, throttling, and blocking all stretch the delay. Measure real time instead.
- Calling the function instead of passing it.
setTimeout(fn(), 100)runsfnimmediately and schedules its return value. - Assuming Node.js matches the browser. Node.js uses a 1 ms minimum, has no nesting clamp, and runs timers in a dedicated phase of its loop. A later chapter covers those phases and how
setTimeout(fn, 0)compares withsetImmediate.
Exercise
What does this code print, and roughly how many milliseconds does the logged value show? const t = Date.now(); setTimeout(() => console.log('B', Date.now() - t), 50); Promise.resolve().then(() => console.log('A')); while (Date.now() - t < 120) {} console.log('C');
Show answer
It prints C, then A, then B with a value of about 120. The busy-wait blocks the stack for 120 ms, so C logs first, at the end of the synchronous code. The promise callback is a microtask and runs as soon as the script's task ends. The timer expired at 50 ms but could not run until the stack was clear, so it reports about 120 ms, not 50.
Exercise
A dashboard uses setInterval(refresh, 1000), where refresh starts a fetch that sometimes takes 3 seconds. Users see overlapping requests and out-of-order updates. What change fixes this, and why?
Show answer
Replace the interval with a recursive setTimeout that schedules the next refresh only after the current fetch settles, for example in a finally block. setInterval fires every second no matter whether the previous request has finished, so slow requests overlap. Scheduling the next run at the end of the current one ensures that only one request is in flight at a time.
Exercise
In a browser, a function reschedules itself with setTimeout(fn, 0) twenty times. Why do the later gaps measure about 4 ms when the early ones are under 1 ms?
Show answer
The HTML specification raises any delay under 4 ms to 4 ms once a timer's nesting level goes past 5. Each rescheduled timer is nested one level deeper than the one that created it, so after about five levels the clamp applies.