Courses / Node.js: From First Script to Production / Chapter 11
Module 6 · Inside the runtime · Chapter 11 of 27
Inside the Event Loop: Phases, Timers and setImmediate
Builds on Getting Started: What Node.js Is and Running Your First Script, Asynchronous Programming: Callbacks, Promises and async/await and Core Modules: Files, Paths, Buffers, Crypto and util. Next up: process.nextTick, Promise Jobs and the Microtask Queue.
Part 1 · The call stack and run to completion
One stack, one thing at a time
A Node server can answer thousands of requests with a single thread of JavaScript. Its turns follow a fixed order, so what runs when can be predicted.
JavaScript in Node runs on one thread. That thread has one call stack: a list of the functions that are running right now, with the newest on top. When a function is called, a frame is pushed on the stack. When it returns, the frame is popped. Only the function at the top is executing.
Code that waits does not sit on the stack. When you call setTimeout, fs.readFile or server.listen, Node hands the waiting to the operating system or to a helper thread, and your function returns at once. Later, when the timer is due or the file has been read, the callback you passed has to run. It cannot run while something else is on the stack, so it waits in a queue.
The event loop is the part of Node that moves callbacks from those queues onto the stack. It is a loop in the plain sense: take the next ready callback, run it, repeat. The getting started chapter showed that one process can serve a second request while the first waits for a database. This chapter explains the machinery behind that.
Run to completion
The rule that makes the whole design easy to reason about is run to completion. Once a callback starts, nothing else on the JavaScript thread can run until it returns. No timer, no incoming request and no other callback interrupts it. Node never pauses one callback to run another.
This is a strength. Between two lines of your code, no other callback can change your variables, so you do not need locks. It is also the one way to hurt a Node server: a callback that runs for a long time holds back every other callback, because they all wait for the stack to empty.
A timer is therefore a promise of a minimum delay, never of an exact time. The timer's callback is queued when the time is up, and it runs when the stack is free and the loop gets round to it. The next page measures this with a loop that does nothing but burn time.
Measuring the delay
The script below asks for a callback after 0 ms. Then it keeps the thread busy for 300 ms. A loop that only checks the clock is the simplest way to model a callback that does heavy work.
const start = performance.now(); setTimeout(() => { const late = Math.round(performance.now() - start); console.log(`timer asked for 0 ms, ran after ${late} ms`); }, 0); const stop = start + 300; while (performance.now() < stop) { // a busy loop: nothing else can run on this thread } console.log('busy loop finished');
busy loop finished timer asked for 0 ms, ran after 302 ms
Node 24.18.0 on Windows. The delay varies a little from run to run.
The setTimeout call comes first in the file, yet its callback runs last. The timer was due after about a millisecond. But the main script was still on the stack for 300 ms, and the callback could not start until that script returned. The callback saw the clock at 302 ms.
Nothing was lost: the callback ran, only late. This is the shape of almost every performance problem in a Node server. A slow piece of code does not fail. It makes everything queued behind it late.
Callbacks do not interrupt each other
Run to completion applies between callbacks as well as between a callback and the main script. In the next script two timers are both due. The first does 50 ms of work.
function slow(name) { const stop = performance.now() + 50; while (performance.now() < stop) {} console.log(`${name} finished`); } setTimeout(() => slow('first timer'), 0); setTimeout(() => console.log('second timer starts'), 0); console.log('main script done');
main script done first timer finished second timer starts
The main script finishes first. Then the first timer runs all the way to its last line, including the 50 ms of work. Only then does the second timer start. Both timers were due at the same moment, but the second had to wait for the stack, because callbacks take turns and never overlap.
Keep this picture for the rest of the chapter. Everything the loop does is about deciding which waiting callback gets the stack next, and the stack is always held by exactly one of them.
| Term | Meaning |
|---|---|
| Call stack | the functions currently running, newest on top |
| Callback | a function Node calls later, when an event is ready |
| Event loop | the loop that takes ready callbacks and runs them on the stack |
| Run to completion | a callback keeps the thread until it returns |
A timer is set for 0 ms, but the main script then runs a 300 ms loop. When does the callback run, and why?
- After the main script returns, so a little over 300 ms in. A callback can start only when the call stack is empty, and the main script holds the stack until it finishes.
Two timers are due together. The first callback takes 50 ms. Can the second start before it finishes?
Part 2 · The phases in order
A turn of the loop
Every Node program runs inside the event loop. If you can name its phases, you can predict how callbacks from timers, files and sockets are ordered.
The loop works in turns. Each turn walks through a fixed list of phases, and each phase owns a first-in, first-out queue of callbacks for one kind of event. When the loop enters a phase, it runs the callbacks in that queue, then moves to the next phase. The Node documentation lists them in this order.
| Phase | What runs there |
|---|---|
| timers | callbacks from setTimeout and setInterval that are due |
| pending callbacks | some deferred system callbacks, such as certain network errors |
| idle, prepare | used inside Node only |
| poll | new I/O events: finished file reads, data arriving on sockets |
| check | callbacks from setImmediate |
| close callbacks | some close events, such as a socket's close |
You will use four of these every day: timers, poll, check and close callbacks. The pending callbacks and the idle and prepare phases are internal, and no API of yours lands in them.
A phase can only start when the previous one is finished, and it runs until its queue is empty or a system limit is reached. A callback added to a queue while that queue is being run waits for the next turn. For setImmediate the docs say so directly: an immediate queued from inside another immediate does not run until the next turn.
Where the timer check sits
The order of the table is the order the Node documentation gives, with the timers phase first. libuv, the C library that implements the loop, changed one detail in version 1.45, which ships with Node 20 and later. It also looks at due timers at the end of each turn, after the close callbacks, and once before the first turn begins. The documentation says this can change the timing of setImmediate against timers in some cases. The next lessons show where it matters.
Not all waiting happens in the loop. A file read, for example, is carried out by a pool thread. When it is done, its result is put into the poll queue as an I/O event, and the loop runs its callback in the poll phase.
One turn, from the poll phase
The script below starts a file read and a socket connection, and waits for the read to finish. That puts the code inside a poll callback. From there it schedules a timer and an immediate, and destroys the socket so that a close event is on its way. A real run shows which phase each of them lands in.
import fs from 'node:fs'; import net from 'node:net'; const server = net.createServer(); server.listen(0, '127.0.0.1', () => { const socket = net.connect(server.address().port, '127.0.0.1'); socket.on('close', () => { console.log('close callbacks: socket closed'); server.close(); }); socket.on('connect', () => { fs.readFile(import.meta.filename, () => { console.log('poll: readFile callback'); setTimeout(() => console.log('timers: setTimeout 0'), 0); setImmediate(() => console.log('check: setImmediate')); socket.destroy(); }); }); });
poll: readFile callback
check: setImmediate
close callbacks: socket closed
timers: setTimeout 0Node 24.18.0 on Linux (WSL), 30 of 30 runs.
Read the output as the order of the loop. The file callback ran in poll. The immediate ran in check, the phase that follows poll. The socket's close callback ran in the close phase. The timer scheduled from the same callback had to wait until the loop reached timers again.
Watch one turn in the scene before reading on.
Watch for each callback waiting for its own phase
Read it as steps
Some orders depend on the system
The same script on Windows gave a different order in some runs. The close callback and the timer swapped places.
win32 {
'poll > check > timers > close callbacks': 15,
'poll > check > close callbacks > timers': 15
}Windows, 30 runs of the same script.
linux { 'poll > check > close callbacks > timers': 30 }Linux (WSL), the same 30 runs.
On Linux all 30 runs agree. On this Windows machine the 30 runs split 15 and 15 between the two orders in this count, and an earlier count gave 19 and 11. On Windows the timer sometimes came before the close callback. The difference is in how the operating system finishes closing a socket, which can move the close event to a later turn. That is why this course treats the phase order as a rule about queues, not a promise about every callback of every kind. Anything that depends on the order of a close event relative to a timer is fragile.
Not every 'close' event comes from the close callbacks phase either. The Node guide says a socket or handle closed abruptly, for example with socket.destroy(), emits 'close' in that phase, and that otherwise the event is emitted through process.nextTick(). The next script closes a server and a UDP socket and shows both events running before a setImmediate callback, which means before the check phase.
import net from 'node:net'; import dgram from 'node:dgram'; const server = net.createServer(); server.listen(0, '127.0.0.1', () => { server.on('close', () => console.log('server close event')); server.close(); const udp = dgram.createSocket('udp4'); udp.on('close', () => console.log('dgram close event')); udp.close(); process.nextTick(() => console.log('nextTick')); setImmediate(() => console.log('setImmediate')); });
server close event dgram close event nextTick setImmediate
Node 24.18.0, same output on Windows and on Linux (WSL).
In which phase does a setImmediate callback run, and which phase comes just before it?
- The check phase. The poll phase comes just before it.
A callback running in the poll phase calls setTimeout(fn, 0) and setImmediate(g). Which runs first on Linux, and why?
Part 3 · The poll phase
What poll does
When the loop reaches poll, the program often has nothing to do. Whether it waits or moves on decides how quickly timers and immediates fire.
The poll phase has two jobs. It works out how long it may wait for I/O, and then it runs the callbacks of the I/O events that have arrived. I/O here means a finished file read, new data on a socket, or a new connection waiting to be accepted.
If the poll queue has callbacks, the loop runs them one after another until the queue is empty or a system limit is reached. If the queue is empty, the loop has a choice. It does not simply keep spinning.
- If some
setImmediatecallbacks are waiting, poll ends at once and the loop moves on to the check phase. - If a timer is due soon, poll waits for I/O until that time and then lets the loop come round to the timers.
- If nothing is waiting at all, poll sleeps until an I/O event arrives. This is where a quiet server spends nearly all of its time.
That waiting is the reason an idle Node server uses almost no processor time. The loop asks the operating system to wake it when something happens, and the thread is asleep in the meantime.
The idle loop costs nothing
The script sets a timer for one second. Then it compares the wall-clock time with the processor time used.
const wall = performance.now(); const cpu = process.cpuUsage(); setTimeout(() => { const used = process.cpuUsage(cpu); const ms = Math.round(performance.now() - wall); const cpuMs = Math.round((used.user + used.system) / 1000); console.log(`waited ${ms} ms of wall time, used ${cpuMs} ms of CPU`); }, 1000);
waited 1014 ms of wall time, used 0 ms of CPU
Node 24.18.0 on Windows. CPU time is rounded to whole milliseconds.
The process waited for 1,014 ms and used less than half a millisecond of processor time, which rounds to 0. The thread did not loop and check the clock. It slept in the poll phase with a timeout equal to the time until the timer was due, and the operating system woke it.
A timer behind a slow I/O callback
The poll phase also shows why timers are late when callbacks are slow. In the next script a timer is due in 50 ms. A file read finishes almost at once, and its callback runs for 150 ms.
import fs from 'node:fs'; const start = performance.now(); setTimeout(() => { const ms = Math.round(performance.now() - start); console.log(`timer set for 50 ms ran after ${ms} ms`); }, 50); fs.readFile(import.meta.filename, () => { const at = Math.round(performance.now() - start); console.log(`readFile callback started at ${at} ms`); const stop = performance.now() + 150; while (performance.now() < stop) {} console.log('readFile callback finished'); });
readFile callback started at 1 ms readFile callback finished timer set for 50 ms ran after 154 ms
Node 24.18.0 on Windows.
The read finished and its callback started at 1 ms. It held the thread until 151 ms or so. The timer was due at 50 ms, but the loop was inside the poll phase running that callback, and it cannot look at timers until the callback returns. The timer fired at 154 ms, more than a hundred milliseconds late.
Late timers are the first sign of an overloaded loop. When a monitor shows timers firing late, the loop is spending too long in some callback. It rarely means the timers themselves are broken.
Poll, immediates and timers together
Put the three rules in one sentence. The loop sleeps in poll only when no immediate is waiting, and it never sleeps past the time of the nearest timer. Because of that, setImmediate is the right tool for "run this after the current I/O is handled", and setTimeout is the right tool for "run this no earlier than this long from now".
The next lesson compares the two on the most common question about them: which one runs first.
Why does an idle Node server use almost no processor time?
- The loop sleeps in the poll phase and the operating system wakes it when I/O arrives or a timer is due, so there is no spinning.
The poll queue is empty and a setImmediate callback is waiting. What does the loop do?
- Poll ends at once and the loop moves on to the check phase, so the immediate runs without waiting.
A 50 ms timer fires after 154 ms because of a 150 ms callback in poll. Is the timer broken?
- No. The callback held the thread, and the loop looks at timers only between callbacks, so the timer ran as soon as the loop could get to it.
Part 4 · setTimeout 0 against setImmediate
Two ways to say "soon"
Both calls schedule a callback for a later turn, and people often assume one of them always wins. Which one runs first depends on where you call them.
setTimeout(fn, 0) asks for fn to run in the timers phase, once at least one millisecond has passed. Node treats a delay of 0 as 1. setImmediate(fn) asks for fn to run in the check phase of the current turn, as soon as poll is finished. The timer has a clock condition and the immediate has none, and that difference is the whole story.
From the main module, the loop has not started yet when both are scheduled. When it starts, it first looks at timers. If the one millisecond has already passed, the timer runs first. If it has not, the loop goes on to check, and the immediate runs first. How long the program took to reach that point depends on the machine and what else is running. The Node documentation therefore says the order is not deterministic in the main module.
From inside an I/O callback, the loop is in the poll phase. The next phase is check, and timers come only after it. The immediate always wins there, whatever the machine is doing.
Counting 20 runs
The script below schedules both calls from the main module and again from a file callback. A second script starts it 20 times and counts the orders it saw.
import fs from 'node:fs'; setTimeout(() => console.log('main: timeout'), 0); setImmediate(() => console.log('main: immediate')); fs.readFile(import.meta.filename, () => { setTimeout(() => console.log('io: timeout'), 0); setImmediate(() => console.log('io: immediate')); });
import { execFileSync } from 'node:child_process'; const seen = {}; for (let i = 0; i < 20; i++) { const out = execFileSync(process.execPath, ['l4-both.mjs'], { encoding: 'utf8', }); const order = out.trim().split(/\r?\n/).join(', '); seen[order] = (seen[order] ?? 0) + 1; } console.log(seen);
{
'main: immediate, main: timeout, io: immediate, io: timeout': 9,
'main: timeout, main: immediate, io: immediate, io: timeout': 11
}One real run of the counter on Windows. The 9 and 11 vary on every run.
The two lines starting with io: are always the same. In all 20 runs the immediate came first. The two lines starting with main: split between two orders, 9 and 11 in this run. Another run of the counter gives other numbers. The point is not the split but that no code can rely on one of the two orders.
Look at one single run next.
main: timeout main: immediate io: immediate io: timeout
One run, printed in full. The first two lines can swap on another run.
Watch for the order flipping once the code runs inside poll
Read it as steps
Which one to use
The scene follows the run above: the timer happened to be due, so it went first in the main module, and then the loop moved to the I/O callback, where the immediate went first. The Node documentation recommends setImmediate where you only mean "after the current work", since its order does not depend on timing.
- Use
setImmediateto let I/O callbacks run before your next step, for example to split a long job into pieces. The thread pool chapter does exactly this. - Use
setTimeoutwhen time is the point: a retry after a delay, a timeout, a pause between polls. - Never use a zero delay timer to wait for another callback you started. Order the work with promises or events instead, so that your code does not depend on a race.
process.nextTick is a third way to say "soon". It is not part of any phase, and it runs before both of these. The next chapter covers it.
In a file callback, setTimeout(a, 0) and setImmediate(b) are both called. Which runs first on any machine?
b. After poll, the next phase is check, and timers are looked at later.
Why is the order of setTimeout(a, 0) and setImmediate(b) not fixed in the main module?
- The loop first checks whether one millisecond has passed since the timer was set. If it has, the timer runs first. If not, the immediate runs first, and that depends on how fast the program reached the loop.
You need a retry 200 ms from now. Which of the two do you use?
setTimeout, because the delay is the point.setImmediatehas no delay.
Part 5 · Timers are minimums
A delay is a lower bound
A timer is not meant to fire early, but how late it fires depends on the system. Measured with performance.now(), a 10 ms timer can read 9 ms, so treat a delay as exact only to about a millisecond. Knowing the limits helps you pick delays and read timings.
The delay you pass to setTimeout is a minimum. The documentation says the callback will likely not run in precisely the delay you gave, and that Node makes no guarantee about exact timing or about ordering. Three things add to it: the clock of the operating system, how busy the loop is, and the checks Node performs on the value.
Node first normalises the value. A delay of less than 1, larger than 2,147,483,647 (about 24.8 days) or not a number is set to 1. A decimal delay is truncated to a whole number. The script below passes 2 to the power of 31, which is one past the limit.
process.on('warning', (w) => { console.log(w.name); console.log(w.message); }); const start = performance.now(); setTimeout(() => { const ms = Math.round(performance.now() - start); console.log(`a 2**31 ms timer fired after ${ms} ms`); }, 2 ** 31);
TimeoutOverflowWarning 2147483648 does not fit into a 32-bit signed integer. Timeout duration was set to 1. a 2**31 ms timer fired after 4 ms
Node 24.18.0. A warning listener prints the warning to stdout here.
Node emitted a warning and ran the callback after 4 ms, not after 24 days. A silently wrong delay is a real bug risk. If you compute a delay from a date, clamp it yourself, and use a timer that checks again later for anything longer than a few days.
The clock sets a floor
The script waits with timers/promises and measures the average real delay for requested delays of 0, 1, 2 and 10 ms, over 100 rounds each. timers/promises gives a promise-based setTimeout that you can await.
import { setTimeout as sleep } from 'node:timers/promises'; async function average(delay, rounds) { const start = performance.now(); for (let i = 0; i < rounds; i++) await sleep(delay); return (performance.now() - start) / rounds; } for (const delay of [0, 1, 2, 10]) { const ms = await average(delay, 100); console.log(`delay ${delay} ms: average ${ms.toFixed(2)} ms`); }
delay 0 ms: average 15.33 ms delay 1 ms: average 15.42 ms delay 2 ms: average 15.47 ms delay 10 ms: average 15.39 ms
Node 24.18.0 on Windows.
Every delay, even 10 ms, came out near 15 ms on this machine (14.97 to 15.51 in a re-run). That is consistent with the default timer tick of Windows, about 15.6 ms: Node's timers wake up on the operating system's clock, so a wait would end on a tick rather than between two ticks. This run does not prove the cause; it shows only the numbers. Here is the same script on Linux in WSL.
delay 0 ms: average 1.13 ms delay 1 ms: average 1.13 ms delay 2 ms: average 2.14 ms delay 10 ms: average 10.26 ms
Node 24.18.0 on Linux (WSL).
On Linux the zero and one millisecond delays cost about 1.1 ms, and the others are close to what you asked for. Both outputs obey the same rule: never earlier than asked, often later. Do not write code that needs a timer to be accurate to a millisecond. The numbers also vary from run to run.
setInterval and missed ticks
setInterval(fn, 50) repeats a callback. The next call is scheduled from the time the previous call started, not from when it ended, so a short callback does not make the period longer. A callback longer than the period delays the next call, and Node does not replay the ticks it missed. The script blocks for 130 ms inside the third tick.
let last = performance.now(); let tick = 0; const timer = setInterval(() => { const now = performance.now(); const gap = Math.round(now - last); console.log(`tick ${tick}: ${gap} ms after the last`); last = now; if (tick === 2) { const stop = now + 130; while (performance.now() < stop) {} } if (++tick === 6) clearInterval(timer); }, 50);
tick 0: 58 ms after the last tick 1: 62 ms after the last tick 2: 62 ms after the last tick 3: 130 ms after the last tick 4: 55 ms after the last tick 5: 62 ms after the last
Node 24.18.0 on Windows. The 50 ms period shows as 53 to 62 ms here.
The ticks arrive about 55 to 62 ms apart on this machine, which is the clock again. Tick 3 came 130 ms after tick 2 began, as soon as the loop was free. Only one tick arrived. The two ticks that would have been due during the block were not repeated, and the next gaps are back to about 60 ms.
A repeating job should therefore never assume that it ran every period. If the work matters, record the time of the last run inside the callback, or schedule the next run yourself after each run finishes.
You call setTimeout(fn, 0). What delay does Node use, and can fn run before it?
- Node uses 1 ms. The callback never runs earlier than that, and it can run later.
A setInterval period is 50 ms and one callback takes 130 ms. How many calls are replayed for the ticks that were missed?
- None. After the long callback the next call runs as soon as the loop is free, and the interval goes on at its normal period.
What does Node do with setTimeout(fn, 2 ** 31)?
- It prints a
TimeoutOverflowWarningand sets the delay to 1 ms, sofnruns almost at once.
Part 6 · What keeps a process alive
Handles decide when Node exits
A Node program ends when the loop has nothing left to wait for. Knowing what counts as something to wait for explains both hanging processes and servers that exit too early.
libuv calls the things the loop waits on handles and requests. An active timer, an open server socket and a pending file read all count. The loop keeps running while at least one active handle is referenced, and it exits when none is left. This is why a script with a pending setTimeout waits for it, and why a script with a listening server does not end by itself.
You can change this for a single timer. timeout.unref() tells the loop that this timer does not need to keep the process alive. If something else keeps the loop going, the timer still fires. If nothing else does, the process exits and the timer never runs. timeout.ref() undoes it. The script below has a 5 second timer marked this way and a normal 100 ms timer.
const start = performance.now(); const background = setTimeout(() => { console.log('background timer ran'); }, 5000); background.unref(); setTimeout(() => { console.log('foreground timer ran'); }, 100); process.on('exit', () => { const ms = Math.round(performance.now() - start); console.log(`process exited after ${ms} ms`); });
foreground timer ran
process exited after 105 msNode 24.18.0 on Windows.
The foreground timer ran, and the process ended 105 ms after it started. The 5 second timer never fired. This is the right tool for housekeeping: a cache cleaner or a metrics flush should not stop the program from exiting.
Measuring the health of the loop
A slow callback is invisible in logs unless you measure it. Node has two built-in measures in perf_hooks.
Event loop delay comes from monitorEventLoopDelay. It runs a timer at a fixed resolution, 10 ms by default, and records the time between firings of that timer, in nanoseconds. When the loop is healthy the values sit near the resolution. When something blocks the loop, one value is large. So the useful number is the maximum, or a high percentile such as percentile(99), compared with an idle baseline. It is not the lateness of your own timers.
Event loop utilization (ELU) comes from performance.eventLoopUtilization(). It reports the share of time the loop spent outside its wait for events, so 0 means fully idle and 1 means always busy. Pass a previous reading and you get the value for the time between the two.
Reading both
The script first stays idle for a second. Then it blocks for 300 ms and waits another second. The histogram keeps running totals from the start, and utilization is measured per window.
import { monitorEventLoopDelay, performance } from 'node:perf_hooks'; const histogram = monitorEventLoopDelay({ resolution: 10 }); histogram.enable(); let before = performance.eventLoopUtilization(); function report(label) { const elu = performance.eventLoopUtilization(before); const ms = (ns) => (ns / 1e6).toFixed(1); const util = elu.utilization.toFixed(2); console.log(`${label}: mean ${ms(histogram.mean)} ms,`, `max ${ms(histogram.max)} ms, window utilization ${util}`); before = performance.eventLoopUtilization(); } setTimeout(() => { report('first second, idle'); const stop = performance.now() + 300; while (performance.now() < stop) {} setTimeout(() => { report('then a 300 ms block'); histogram.disable(); }, 1000); }, 1000);
first second, idle: mean 15.5 ms, max 16.0 ms, window utilization 0.00 then a 300 ms block: mean 17.9 ms, max 319.6 ms, window utilization 0.23
Node 24.18.0 on Windows.
first second, idle: mean 10.1 ms, max 10.2 ms, window utilization 0.00 then a 300 ms block: mean 11.7 ms, max 311.2 ms, window utilization 0.23
Node 24.18.0 on Linux (WSL), for the baseline.
While idle, the delay sits at the sampling resolution plus the clock: about 15.5 ms on this Windows machine and about 10.1 ms on Linux. The baseline depends on the system, so read your own idle value first. After the block the maximum jumped to about 310 to 320 ms, the length of the block, and utilization for the window was 0.23: the loop was busy for 300 ms of about 1.3 s.
The two together tell different things. Utilization says how busy the loop is. The delay maximum says how long it was ever unavailable, which is what a waiting request feels. Alert on both in a real service. The profiling chapter uses them under load.
| Term | Meaning |
|---|---|
| Handle | an object libuv waits on, such as a timer or a socket |
| Referenced | counted when the loop decides whether to exit |
All chapters · Previous: Advanced Topics: Child Processes, Worker Threads, Cluster and Debugging