Careeroza
The Event Loop
How JavaScript Handles Async Work
- The call stack runs synchronous code.
- Async work (timers, network) is handed to the browser/Node and runs in the background.
- 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.
- 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)