The event loop
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// 1, 4, 3, 2
A timer set to 0 still runs last, and the printed order surprises almost everyone. JavaScript runs your code on a single call stack. Asynchronous work is handed off to the host (the browser or Node), and when it finishes, its callback is queued. The event loop takes callbacks from the queues and pushes them onto the stack — but only when the stack is empty.
There are two queues that matter, and they run in a strict order:
- The macrotask queue holds timers (
setTimeout,setInterval), I/O, and UI events. - The microtask queue holds Promise callbacks (
.then,awaitcontinuations) andqueueMicrotask.
After every macrotask, the event loop drains the entire microtask queue
before the next macrotask. So a setTimeout(fn, 0) scheduled before a resolved
Promise.then still runs after the .then, because microtasks always go
first.
A setTimeout(…, 0) is not "immediately" — it waits for the current task and
all pending microtasks.
You are about to answer a short quiz on the event loop.