Sub topic 7
The Event Loop in Both Runtimes
This chapter assumes you can write promises and setTimeout calls, and that you know how to run a script in the browser and with node. It explains the scheduling model the browser and Node.js share, and the places where Node.js adds its own phases.
One thread, many queues
A JavaScript engine runs your code on a single thread through a call stack. When the stack empties, the host runtime decides what runs next. The event loop is the host's scheduler. It picks the next piece of queued work, runs it to completion, and repeats.
The host queues two kinds of work:
- A task (also called a macrotask) is a unit of work such as running a script, a timer callback, a UI event, or an I/O completion.
- A microtask is a short follow-up job, usually a promise reaction (
.then,awaitresumption) or aqueueMicrotaskcallback.
The core rule is the same in both runtimes. After each task finishes, the runtime drains the whole microtask queue before it starts another task. If a microtask queues more microtasks, those run too, all before the next task.
console.log('1: sync');
setTimeout(() => console.log('4: timer task'), 0);
Promise.resolve().then(() => console.log('3: microtask'));
console.log('2: sync');The script itself is the current task, so both console.log calls run first. Next the microtask queue is drained, and only then does the timer task get a turn. A delay of 0 means "as soon as a task slot is free". It never means "immediately".
The browser loop
The browser runs a task, drains microtasks, and then may take a rendering opportunity: it runs requestAnimationFrame callbacks, recalculates styles and layout, and paints. Rendering happens only between tasks, so a long task or an endless microtask chain freezes the page. A microtask that keeps queuing microtasks is worse than a long timer loop, because the browser never reaches the render step.
The Node.js loop
Node.js builds its loop on the libuv library, which splits each iteration into phases. Each phase has its own callback queue.
| Phase | What runs there |
|---|---|
| timers | `setTimeout` and `setInterval` callbacks whose time has passed |
| pending callbacks | some deferred system I/O callbacks |
| poll | new I/O events; the loop waits here when it has nothing else to do |
| check | `setImmediate` callbacks |
| close callbacks | `'close'` handlers such as `socket.on('close')` |
Since Node.js 11, microtasks are drained after every individual callback, which matches browser behavior. Node.js also has a queue that runs before promise microtasks: the process.nextTick queue.
// order.cjs (run with: node order.cjs)
const fs = require('node:fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
});The output is nextTick, promise, immediate, timeout. The I/O callback runs in the poll phase, so after its microtasks the loop moves on to the check phase (setImmediate) before it wraps around to the timers phase.
Common errors
- Treating
setTimeout(fn, 0)as "next". Every pending microtask runs first, and browsers clamp nested timers to at least 4 ms. - Starving the loop. Recursive
process.nextTickor promise chains stop I/O and timers from ever running. - Blocking with CPU work. A loop that runs for 2 seconds delays every timer, click handler, and network callback by 2 seconds. A later chapter moves this work onto workers.
Exercise
Run this as a CommonJS file with node. What does it print, and why? console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); process.nextTick(() => console.log('D')); console.log('E');
Show answer
A, E, D, C, B. The synchronous logs A and E run first as part of the script task. Then the nextTick queue (D) runs, then the promise microtask queue (C). The timer callback B runs last, in the timers phase of a later loop iteration.
Exercise
A browser page runs function loop() { Promise.resolve().then(loop); } loop();. Will a button click handler or a repaint ever run? Explain.
Show answer
No. Each microtask queues another microtask, so the microtask queue never empties. The event loop can't finish the current turn, which means it never picks the next task (the click) and never reaches the rendering step. The page freezes.