Skip to content

The event loop: why setTimeout(0) waits

Working knowledgeUnder the hood

You ask for a timer of zero milliseconds and it still runs after code written below it, and after every promise callback too. Here is the loop that decides what runs next, drawn one tick at a time: the call stack, the task queue and the microtask queue.

01 A zero-millisecond timer that runs last

The timer is set up second and asks for no delay at all. The letters in the logs show the order things actually come out.

loop.mjs
console.log('A');
setTimeout(() => {
console.log('E');
}, 0);
Promise.resolve()
.then(() => console.log('C'))
.then(() => console.log('D'));
console.log('B');
Shell
node loop.mjs
Text
A
B
C
D
E

That is a real run on Node 24, and every browser prints the same. The timer’s E comes last, after both promise callbacks, even though D was not even queued until C had run.

02 Zero milliseconds does not mean now

It is tempting to read setTimeout(fn, 0) as “run fn now” and a promise callback as “run this when the value is ready”. Neither is true. Both only queue a callback. Your JavaScript runs on one thread, and a queued callback can start only when that thread has nothing else on its stack.

The naive readingRuns at oncefn would interrupt the script and E would be logged second.
What the delay meansNot beforeThe delay is a minimum. The callback joins a queue once it has passed and runs when the loop gets to it.

03 The stack, two queues and one rule

The engine (V8, SpiderMonkey, JavaScriptCore) runs code on a call stack. The host around it, the browser or Node, owns the event loop and feeds it callbacks from queues. There are two kinds that matter here.

Where callbacks wait
QueueWhat lands thereWhen it runs
Task queuetimers (setTimeout, setInterval), I/O callbacks, user events, messagesOne task per turn of the loop
Microtask queuepromise callbacks (then, catch, finally), the code after an await, queueMicrotaskAll of them, whenever the stack empties

Browsers have several task queues (for example one for user input and one for timers) and choose between them; the spec only promises that tasks from the same source keep their order. The loop itself follows one rule:

  • Take one task and run it until the stack is empty. Nothing interrupts it.
  • Run every microtask, including ones queued while doing so, until the microtask queue is empty.
  • In a browser, render the page if it is time to (typically about 60 times a second).
  • Go back to the first line, or wait if there is nothing to do.

This is why promise callbacks always beat timers: the script that queued them is itself a task, and the microtasks are drained the moment it ends, before the loop looks at the task queue again.

04 What really happens, tick by tick

Here is loop.mjs again, with the stack, both queues and the log side by side. The chip says which part of the loop’s rule is in force.

loop.mjs, tick by tick
Step 1 of 13
Call stack
scripttop
Task queue
Empty
Microtask queue
Empty
Logged
Empty
  • just added
  • running

The script itself is the first piece of work. It runs on the call stack; both queues are empty and nothing has been logged.

running the script loop is

The trace shows the timer callback joining the task queue at once to keep it short. Strictly, the host adds it when the timer expires: in Node a delay of 0 is treated as 1 ms. The order is the same either way, because the task cannot start until the script and every microtask are done.

05 See the loop wait for you

A timer cannot cut into running code. Keep the thread busy for 200 ms and a 0 ms timer waits the whole time.

block.mjs
const start = Date.now();
setTimeout(() => {
console.log(`timer ran after ${Date.now() - start} ms`);
}, 0);
while (Date.now() - start < 200) {} // 200 ms of busy work
console.log('busy loop done');
Text
busy loop done
timer ran after 201 ms

A real run; your number will be close to 200 but not exactly the same. Microtasks can starve timers in the same way. Each microtask below queues the next, and the loop must drain the queue before it touches a task, so the timer waits for a million of them.

starve.mjs
setTimeout(() => console.log('timer finally ran'), 0);
let n = 0;
function again() {
if (++n < 1_000_000) queueMicrotask(again);
else console.log('microtasks done:', n);
}
queueMicrotask(again);
Text
microtasks done: 1000000
timer finally ran

In a browser the same two programs freeze the page: rendering also happens only between tasks, so while the stack is busy or the microtask queue keeps refilling, nothing is painted and clicks are not handled.

06 Node adds its own queues

Node’s loop comes from the libuv library and runs in phases. Each phase has its own queue of tasks; between callbacks, Node drains its process.nextTick queue and then the promise microtasks.

Node’s main loop phases, in order (simplified)
PhaseRuns
timerssetTimeout and setInterval callbacks whose time has come
pollI/O callbacks: files, sockets; waits here when idle
checksetImmediate callbacks
closeclose events, such as a socket’s close
tick.cjs
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
Text
sync
nextTick
promise
timeout
immediate

A real run on Node 24, as a CommonJS file. Two details are easy to trip on. Saved as tick.mjs instead, the same code printed promise before nextTick, because Node runs an ES module’s top-level code from inside promise machinery and drains those microtasks first. And from the main script the order of timeout and immediate is not guaranteed; it depends on whether 1 ms has passed when the loop starts. Inside an I/O callback, setImmediate always runs first, because the check phase comes straight after poll.

07 When it bites

app.get('/report', (req, res) => { const data = JSON.parse(hugeString); res.json(summarise(data)); });Slow synchronous work in a serverWhile one request parses, no other request is even read. Move heavy work to a worker thread, stream it, or split it into chunks.
function poll() { check().then(poll); }A microtask loop that never yieldsIf check() returns an already settled promise, poll queues itself forever and timers, I/O and rendering never get a turn. Yield with setTimeout or setImmediate between rounds.
for (const row of rows) { await process(row); }Thinking await lets the page paintIf process settles at once, every await resumes as a microtask and the browser still cannot render until the whole loop ends. To give it a frame, await a task, e.g. await new Promise((r) => setTimeout(r)).
setTimeout(tick, 0); // nested 5 deepExpecting 0 ms to be fastBrowsers raise the delay of deeply nested timers (five levels or more) to at least 4 ms, and background tabs throttle timers much more. Do not use timers for precise timing.

Every callback runs to completion. If one handler takes 300 ms, everything else (other requests, clicks, timers, painting) waits 300 ms, however short their own work is.

08 Check yourself

Question

setTimeout(() => log('t'), 0); queueMicrotask(() => log('m')); log('s'); In what order are the letters logged?

Question

A microtask queues another microtask. When does the second one run?

Question

Why does setTimeout(fn, 0) not run fn straight away?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?