๐Ÿ”„ JavaScript

The JavaScript Event Loop โ€” Explained With One Example

๐Ÿ“… Jun 17, 2026 โฑ 4 min read

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, 2

Why that order

  1. Sync code first: 1, 4 โ€” straight down the call stack
  2. Microtasks next: promise callbacks (3) โ€” the entire microtask queue drains
  3. 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

โ† All Articles