JavaScript runs one thing at a time, yet handles thousands of async events. The event loop is the mechanism โ and interviewers love asking you to predict output.
The question they always ask
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2Why that order
- Sync code first: 1, 4 โ straight down the call stack
- Microtasks next: promise callbacks (3) โ the entire microtask queue drains
- Macrotasks last: setTimeout (2) โ one per loop turn
setTimeout(fn, 0) never means "now" โ it means "after all sync code AND all pending microtasks".
Why it matters practically
- A long sync loop freezes clicks, scrolling, everything โ offload heavy work to Web Workers (our DSA judge does exactly this)
- UI updates batch between loop turns โ that is why frameworks feel instant