Sub topic 7
The Event Loop in Both Runtimes
This chapter assumes you know what a promise is, can write an async function, and have read the earlier chapters on engines and runtimes. The engine runs your code on a single thread with a call stack. The event loop belongs to the host. It decides which piece of code the engine runs next. Browsers and Node.js use the same basic model, but each has its own extra queues and ordering rules, and those differences cause real bugs.
The Working Model
Three ideas cover most of the behavior you will see.
- Run to completion. When a function starts running, nothing else on that thread interrupts it. A callback can only start after the call stack is empty.
- Tasks. A task (also called a macrotask) is a unit of work the host schedules. Timer callbacks, I/O completions, and UI events are all tasks. The loop takes one task, runs it to completion, and then moves on.
- Microtasks. A microtask is a small job that runs right after the current task finishes, before the next task starts. Promise reactions (
.then,.catch,.finally), the code that resumes after anawait, andqueueMicrotaskcallbacks are microtasks. The loop drains the microtask queue completely, so microtasks queued during this step also run before anything else.
The core cycle looks like this:
You run the whole script as the first task. That is why this example prints in numeric order in both runtimes:
console.log('1: sync');
setTimeout(() => console.log('4: timer task'), 0);
Promise.resolve().then(() => console.log('3: microtask'));
console.log('2: sync');The synchronous lines run first because the script is still on the stack. When the script finishes, the loop drains the microtask queue and prints 3. The timer callback is a separate task, so it runs on a later turn.
`await` Splits a Function
An async function runs synchronously until its first await. The rest of the function resumes later as a microtask.
async function work() {
console.log('A: before await');
await null;
console.log('C: after await (microtask)');
}
work();
console.log('B: caller continues');The output is A, B, C. Developers often expect C before B because the code "looks" sequential. The caller always gets control back at the first await, even when the awaited value is already available.
The Browser's Loop
The HTML specification defines the browser loop. A browser has several task sources, such as timers, user input, networking, and postMessage. It may prioritize between them. Input events, for example, often go ahead of timers. Inside a single source, tasks run in order.
The main thread of a page also handles rendering. After a task and its microtasks finish, the browser may run a rendering step. Rendering usually happens about once per display refresh, roughly every 16.7 ms at 60 Hz. During that step it does the following:
- runs
requestAnimationFramecallbacks, - recalculates styles and layout,
- paints.
// Paste into a browser console
setTimeout(() => console.log('timeout'), 0);
requestAnimationFrame(() => console.log('animation frame'));
Promise.resolve().then(() => console.log('microtask'));
console.log('sync');sync and microtask always come first. Whether timeout or animation frame comes next depends on where the browser is in its frame cycle. Do not write code that depends on that order. Use requestAnimationFrame for visual updates, because it runs just before paint. Use timers for work that has nothing to do with frames.
Browsers also change how timers behave:
- Once timers are nested more than five levels deep, a
setTimeout(fn, 0)is clamped to at least 4 ms. - Background tabs throttle timers heavily, often to once per second or less.
MutationObservercallbacks are microtasks, so they run before the next render.
The Node.js Loop
Node.js builds its loop on libuv, a C library for asynchronous I/O. Each turn of the libuv loop goes through a fixed set of phases, and each phase has its own queue of callbacks.
| Phase | What runs there |
|---|---|
| timers | Callbacks from `setTimeout` and `setInterval` whose delay has passed |
| pending callbacks | Some system-level callbacks deferred from the previous iteration, such as certain TCP errors |
| poll | Most I/O callbacks (file reads, sockets). The loop blocks here and waits for I/O if nothing else is pending |
| check | `setImmediate` callbacks |
| close callbacks | `'close'` events, such as `socket.on('close')` |
Since Node.js 11, Node drains the microtask queues after each timer or immediate callback, not only between phases. Browsers behave the same way.
`process.nextTick` Comes Before Promises
Node.js has a second microtask-like queue for process.nextTick callbacks. Node drains it before the promise microtask queue. Save this file as order.cjs and run node order.cjs:
// order.cjs
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));
console.log('sync');You will see sync, nextTick, promise. Then timeout and immediate print in either order. A setTimeout(fn, 0) actually uses a delay of 1 ms. Whether that 1 ms has passed when the loop first enters the timers phase depends on how fast the process started.
When `setImmediate` Order Is Guaranteed
Inside an I/O callback, the order becomes deterministic. The loop is in the poll phase. The check phase, which runs setImmediate, comes next, and the timers phase does not come around again until the next iteration.
// io-order.cjs
const fs = require('node:fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});This prints immediate and then timeout every time. To yield to the loop after I/O, use setImmediate. To yield before any I/O can run, use queueMicrotask or a resolved promise.
Comparing the Two Loops
| Feature | Browser | Node.js |
|---|---|---|
| Promise microtasks | Yes | Yes |
| `queueMicrotask` | Yes | Yes |
| Extra high-priority queue | None | `process.nextTick` |
| `setImmediate` | Not standard | Check phase |
| Rendering step | Yes, with `requestAnimationFrame` | None |
| Minimum timer delay | 4 ms clamp after deep nesting | 1 ms (`0` becomes `1`) |
| Task ordering | Per task source, the browser may prioritize | Fixed phase order |
| Loop exits when idle | Never while the page is open | Yes, when nothing is scheduled or open |
The last row is important for Node.js. A script exits once no timers, sockets, or other handles remain. An open server or an active setInterval keeps the process alive. timer.unref() tells Node not to wait for that timer.
Failure Modes
Blocking the Loop
The loop cannot run a callback while synchronous code is running. A timer delay is a minimum, not a guarantee:
const start = Date.now();
setTimeout(() => {
console.log(`timer fired after ${Date.now() - start} ms`);
}, 10);
while (Date.now() - start < 200) {
// busy-wait: simulates CPU-heavy synchronous work
}This code prints about 200 ms, not 10. In a browser the page freezes for that time. In a Node.js server every other request waits. To fix it, split the work into chunks scheduled as separate tasks, or move it to a worker (covered in a later chapter).
Starving the Loop with Microtasks
Microtasks are drained completely, so a microtask that keeps queuing another one blocks timers, I/O, and rendering:
let count = 0;
setTimeout(() => console.log(`timer ran after ${count} microtasks`), 0);
function spin() {
if (++count < 1_000_000) queueMicrotask(spin);
}
spin();The timer reports 1,000,000. Without the limit, it would never run at all. Recursive process.nextTick calls starve the loop the same way. Use setTimeout or setImmediate for repeated work that should let other callbacks in.
Common Mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Expecting `setTimeout(fn, 0)` to run "now" | It runs after all microtasks and possibly after other tasks | Use `queueMicrotask` if it must run before the next task |
| Relying on `timeout` vs `immediate` order at top level | Results vary between runs | Schedule from inside an I/O callback, or don't depend on the order |
| Assuming code after `await` runs before the caller continues | Wrong ordering, race conditions | Remember that `await` always yields |
| Long loops on the main thread | Frozen UI, stalled server | Chunk the work or use workers |
| Recursive `nextTick` or microtasks | I/O and rendering starve | Yield with a task instead |
Exercise
Run as a CommonJS file in Node.js, what does this print, and in what order? setTimeout(() => console.log('T'), 0); Promise.resolve().then(() => { console.log('P1'); process.nextTick(() => console.log('N2')); }).then(() => console.log('P2')); process.nextTick(() => console.log('N1')); console.log('S');
Show answer
S, N1, P1, P2, N2, T. The script is the first task and prints S. Node drains the nextTick queue (N1), then the promise queue. P1 queues N2, but Node is still draining promise microtasks, so P2 runs first. After the promise queue is empty, Node checks the nextTick queue again and prints N2. The timer runs on a later turn and prints T.
Exercise
A browser handler runs a 300 ms calculation and then sets element.textContent = 'done'. Before the calculation, it sets element.textContent = 'working…'. Why does the user never see "working…", and what is one fix?
Show answer
Rendering happens only between tasks, after microtasks. The whole handler is one task, so both text changes happen before the browser gets a chance to paint, and only "done" appears. One fix is to set "working…" and then start the calculation in a later task, for example with setTimeout(compute, 0) or inside a requestAnimationFrame callback that schedules the work after the frame. Moving the calculation to a Web Worker also works.
Exercise
Inside a fs.readFile callback, you call setTimeout(a, 0) and setImmediate(b). Which one runs first, and why is this ordering guaranteed when the same calls at the top level are not?
Show answer
b runs first. The I/O callback runs in the poll phase, and the check phase, where setImmediate callbacks run, comes right after it. The timers phase does not come around again until the next iteration. At the top level, the order depends on whether the 1 ms timer delay has passed when the loop first enters the timers phase, and that varies from run to run.