JavaScript Interview Question #154
Why does setTimeout(fn, 0) not execute immediately?
Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced
Quick Interview Answer
A zero-millisecond timeout means the callback becomes eligible to run after the minimum scheduling delay; it does not interrupt currently executing JavaScript. The callback is placed into the runtime's task scheduling mechanism and must wait for the current call stack and relevant microtasks to finish.
Detailed Explanation
A zero-millisecond timeout means the callback becomes eligible to run after the minimum scheduling delay; it does not interrupt currently executing JavaScript. The callback is placed into the runtime's task scheduling mechanism and must wait for the current call stack and relevant microtasks to finish.
This is why synchronous statements and already-scheduled Promise microtasks can execute before a zero-delay timer.
Code Example
console.log("A");
setTimeout(() => {
console.log("Timer");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("B");
// A, B, Promise, Timer