Event loop
JavaScript runs on a single thread, yet timers, fetch and clicks all work without blocking. The event loop is the mechanism behind that, and its microtask vs macrotask order is the answer to the classic output-order puzzles asked in interviews.
15.1 The problem: a late 0 ms timer
- setTimeout(..., 0) is scheduled, then a while loop keeps the CPU busy for 3 seconds.
- You might expect Timer done immediately, but it prints last, after 3 seconds.
console.log("Order placed"); setTimeout(() => { console.log("Timer done");}, 0); const start = Date.now();while (Date.now() - start < 3000) { // 3 seconds ka heavy kaam} console.log("Heavy work done");Order placedHeavy work doneTimer done15.2 Why was the timer late?
- JavaScript has one call stack; while code runs on it, no other callback can run.
- The timer callback was ready after 0 ms but waited in the queue while the loop blocked the stack.
- The setTimeout delay is a minimum time, not a guarantee; the callback runs only when the stack is empty.
15.3 The 4 parts of the event loop
| Part | What it does | Examples |
|---|---|---|
| Call stack | Runs synchronous code line by line | console.log, loops, function calls |
| Web APIs | Browser (or Node) does async work in the background, outside JS | Timers, fetch, click events |
| Queues | Ready callbacks wait in line | Microtask queue, macrotask (task) queue |
| Event loop | When the stack is empty, moves the next callback to it | Repeats forever |
- Step 1
1.Run all synchronous code on the call stack
- Step 2
2.Stack empty -> run ALL microtasks (Promise then/catch, code after await)
- Step 3
3.Microtask queue empty -> browser may update the screen
- Step 4
4.Take ONE macrotask (setTimeout, click) and run it
- Step 5
5.Run all microtasks again, then repeat
Microtasks always go before the next macrotask
15.4 Classic puzzle: 1, 2, 3, 4
console.log("1"); setTimeout(() => { console.log("2");}, 0); Promise.resolve().then(() => { console.log("3");}); console.log("4");1432- Sync code runs first: 1, then 4.
- The timer callback goes to the macrotask queue; the then callback goes to the microtask queue.
- Stack empty: all microtasks run, so 3.
- Then one macrotask runs, so 2 comes last.
15.5 Checkpoint: async/await in the order
console.log("A"); setTimeout(() => console.log("B"), 0); async function run() { console.log("C"); await null; console.log("D");} run();Promise.resolve() .then(() => console.log("E"));console.log("F");ACFDEB- Step 1
1.Sync: A; B's timer -> macrotask queue
- Step 2
2.run() starts: C prints synchronously
- Step 3
3.await null -> rest of run (D) becomes a microtask
- Step 4
4.then(E) -> microtask queued after D; F prints (sync)
- Step 5
5.Microtasks in order: D, E
- Step 6
6.Macrotask: B
15.6 Comparison: microtask vs macrotask
| Point | Microtask | Macrotask (task) |
|---|---|---|
| Sources | Promise then/catch/finally, code after await, queueMicrotask | setTimeout, setInterval, click/DOM events, I/O |
| How many per turn | All of them, until the queue is empty | One |
| Order vs the other | Before the next macrotask | After all microtasks |
| Risk | Endless chain blocks screen updates | Delay is only a minimum |
15.7 Common mistake: a heavy loop freezes the page
- One long loop over thousands of orders keeps the stack busy: clicks and scrolling do nothing.
- Fix: process in chunks and yield to the event loop every 1000 items with a tiny await.
- For really heavy calculations, move the work to a Web Worker.
// Wrong: page frozen until the loop endsfunction processAll(orders) { for (const order of orders) { calculateBill(order); } showDone();} // Right: a break every 1000, clicks still workasync function processAll(orders) { for (let i = 0; i < orders.length; i++) { calculateBill(orders[i]); if (i % 1000 === 0) { await new Promise((r) => setTimeout(r)); } } showDone();}15.8 Misconceptions and rules
- await does not stop the program; only that async function pauses (F printed before D).
- setTimeout 0 does not mean immediately: it runs after the current code and after all microtasks.
- Do not run long synchronous work on the main thread: chunks or a Web Worker.
- Do not create endless microtask chains: the screen cannot update until the microtask queue is empty.
- Node uses the same event loop idea, with slightly different phases.
15.9 Interview tips
- JavaScript is single threaded; async work (timers, fetch) is handled by Web APIs.
- Finished work puts callbacks in queues; the event loop moves them to the stack when it is empty.
- All microtasks run before every macrotask, so Promise.then beats setTimeout 0.
- Code after await is a microtask.
- Walk through 1, 4, 3, 2 out loud when given an ordering puzzle.