Sub topic 2
What setTimeout(fn, 0) Really Means
This chapter assumes you know callbacks, basic Promise usage, and async/await syntax, plus the call stack and task queue from the previous chapter.
Timers Set a Minimum Delay
setTimeout(fn, 0) does not mean "run now." It asks the host to queue fn as a task once at least 0 ms have passed. That task can only run when the call stack is empty, so synchronous code that blocks the thread also delays the timer.
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 Microtask Queue
The microtask queue is a second queue with higher priority than the task queue. Each time the call stack empties, the engine drains the whole microtask queue before the event loop picks the next task. Microtasks that get queued while the queue is draining also run in that same pass.
Promises Run as Microtasks
A .then callback is a promise reaction. When the promise settles, the reaction is queued as a microtask. That is why a promise callback runs before a zero-delay timer:
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// Output: A, D, C, BThe synchronous lines print A and D. Then the microtask prints C. Last, the timer task prints B.
async/await Under the Hood
An async function runs synchronously until its first await. At that point it pauses. Its continuation, the code after the await, is scheduled as a microtask once the awaited value resolves.
async function run() {
console.log('1');
await null;
console.log('3');
}
run();
console.log('2');
// Output: 1, 2, 3Exercise
What does this print? setTimeout(() => console.log('x'), 0); (async () => { console.log('y'); await 0; console.log('z'); })(); console.log('w');
Show answer
y, w, z, x. The async function logs y synchronously. Then w prints. The continuation after await runs as a microtask and logs z. The timer task logs x last.