setTimeout(fn, 0)
setTimeout(fn, 0) does not run the function immediately, as it might seem!
It puts the fn callback into a queue to run after the current code, that is, asynchronously, on the next iteration of the event loop.
What happens
javascript
setTimeout(() => console.log('timeout'), 0);
console.log('main');Output:
javascript
main
timeoutEven though the delay is 0, JS first finishes the whole current stack (everything synchronous), and only then runs the callbacks from the timer queue (callback queue).
Why this happens
JavaScript is single-threaded.
All asynchronous operations (setTimeout, fetch, Promise) go into the event queue
and run only after the call stack becomes empty.
What setTimeout(fn, 0) is used for
Deferring code execution to:
- wait for the current operations to finish;
- avoid blocking the interface;
- run code "after everything else";
- let the browser update the DOM before execution.
Example:
javascript
console.log('A');
setTimeout(() => console.log('B'), 0);
console.log('C');Output:
javascript
A
C
BSummary
| What it does | Puts the callback in the queue for the next event loop iteration |
|---|---|
| Delay time | At least 0 ms, but actually a bit later |
| Execution | After all synchronous code |
| Used for | Deferred code, synchronization, avoiding UI blocking |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.