Skip to main content

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 timeout

Even 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 B

Summary

What it doesPuts the callback in the queue for the next event loop iteration
Delay timeAt least 0 ms, but actually a bit later
ExecutionAfter all synchronous code
Used forDeferred code, synchronization, avoiding UI blocking

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.