The Event Loop

How JavaScript Handles Async Work

  1. The call stack runs synchronous code.
  2. Async work (timers, network) is handed to the browser/Node and runs in the background.
  3. When it finishes, its callback is put in a queue: promise callbacks go to the microtask queue, timers and events to the task (macrotask) queue.
  4. When the stack is empty, the event loop runs all microtasks, then one task, then repeats.

Predict the Output

Example

A classic interview question. Synchronous code first, then microtasks (promises), then tasks (timers):

console.log("A");
setTimeout(() => console.log("B (timeout)"), 0);
Promise.resolve().then(() => console.log("C (promise)"));
queueMicrotask(() => console.log("D (microtask)"));
console.log("E");

Output

A
E
C (promise)
D (microtask)
B (timeout)