Javascript Fundamentals · Interview Fundamentals

The event loop

microtasks and macrotasks

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, await continuations) and queueMicrotask.

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.

  1. Microtasks run after the currently executing macrotask, before the next macrotask.
  2. Promise callbacks such as .then are scheduled on the ___ queue.
  3. setTimeout(fn, 0) runs before a pending resolved Promise.then callback.
  4. setTimeout, setInterval, and I/O callbacks are examples of ___ tasks.
  5. The event loop only pushes a queued callback onto the call stack when the stack is empty.
  6. For console.log('1'); setTimeout(() => log('2'), 0); Promise.resolve().then(() => log('3')); console.log('4'), the order is 1, 4, ___, 2.
  7. The event loop drains the entire microtask queue after each macrotask.