Zero Delay Doesn't Mean Immediate
What you'll learn: Why setTimeout(fn, 0) doesn't run your function instantly, even though the delay is zero.
The Surprising Truth About Zero-Delay Timers
When you call setTimeout(fn, 0), you might expect your function to execute immediately—after all, the delay is zero milliseconds! But here's what actually happens: your function goes into the task queue and waits for the current call stack to completely clear before running.
Why the Wait?
Remember that JavaScript is single-threaded. The event loop can only pick up tasks from the queue after all synchronous code finishes executing. Even with a zero delay, setTimeout schedules a task for "later"—and "later" means "after the stack is empty."
Analogy: The Restaurant Kitchen
Think of the call stack as a chef finishing orders already on the counter (synchronous code). Even if someone places a "rush" order with zero wait time (setTimeout(fn, 0)), it still goes to the back of the order queue. The chef must finish current orders first before checking the queue.
Example Execution Order
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');
Output:
Start
End
Timeout
Even though the timeout is 0, it prints last because console.log('End') is synchronous—it's already on the call stack and executes immediately. The timeout callback must wait in the task queue until the stack clears.
Key Takeaway: setTimeout(fn, 0) doesn't mean "run now"—it means "run as soon as the current synchronous code finishes and the call stack is empty."