The Node.js event loop
Overview
You met the event loop in JavaScript Essentials: when the call stack is empty, run all microtasks, then take the next task. Node’s event loop follows the same idea but is more detailed, because a server juggles timers, network I/O, file I/O and more.
Most of the time you don’t need these details — async/await just works. But they explain puzzling orderings, help you write code that yields fairly to other requests, and come up in interviews.
The phases
The loop, provided by libuv, goes round and round through a fixed set of phases. Each phase has a queue of callbacks to run.
- timers — callbacks from
setTimeoutandsetIntervalwhose time has come. - pending callbacks — a few system-level callbacks deferred from the previous turn.
- poll — retrieve new I/O events (a socket received data, a file finished reading) and run their callbacks. If nothing else is scheduled, the loop waits here for I/O.
- check — callbacks scheduled with
setImmediate. - close callbacks — e.g.
socket.on('close', …).
(Libuv also has internal “idle/prepare” steps you never interact with.)
Microtasks: nextTick and promises
Between phases — and in fact after every single callback — Node empties two special queues, in this order:
- The
process.nextTickqueue. - The promise microtask queue (
.thencallbacks, code afterawait,queueMicrotask).
setTimeout(() => {
console.log('timeout');
process.nextTick(() => console.log('nextTick inside timeout'));
Promise.resolve().then(() => console.log('promise inside timeout'));
}, 0);
setTimeout(() => console.log('second timeout'), 0);
// timeout
// nextTick inside timeout
// promise inside timeout
// second timeoutBoth microtask queues run before the second timer, even though both timers were due.
One quirk: at the top level of an ES module, the module’s own code runs inside a promise job, so promise callbacks scheduled there run before
process.nextTickcallbacks. Inside timers, I/O callbacks and CommonJS files, nextTick comes first as described above. You rarely need to care — but it explains surprising results when you experiment.
setImmediate vs setTimeout(…, 0)
Both mean “soon”, but they live in different phases:
setTimeout(fn, 0)runs in the timers phase (with a minimum delay of about 1 ms).setImmediate(fn)runs in the check phase, right after polling for I/O.
From the main script their order isn’t guaranteed — it depends on how quickly the process started. But inside an I/O callback, setImmediate always wins, because the check phase comes straight after the poll phase:
import { readFile } from 'node:fs';
readFile(import.meta.filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
// immediate
// timeout — always in this orderWhen does Node exit?
Node keeps the loop running while there’s anything that could still produce a callback: active timers, open servers, sockets, file operations, child processes. When nothing is left, the process exits by itself.
That’s why a script that only reads a file exits automatically, while a server keeps running until you stop it. If a script you expect to finish keeps hanging, something is still open — an unclosed database pool, a forgotten setInterval, a socket.
You can let a timer not keep the process alive with .unref():
const timer = setInterval(sendMetrics, 10_000);
timer.unref(); // don't keep running just for thisPractical lessons
Long loops should yield
A request handler that processes 100,000 items in one go blocks every other request until it finishes. Splitting the work into chunks, with a pause between them, gives the loop a chance to serve others:
import { setImmediate as yieldToLoop } from 'node:timers/promises';
async function processAll(items) {
for (let i = 0; i < items.length; i++) {
handle(items[i]);
if (i % 1000 === 0) await yieldToLoop(); // let I/O and other requests run
}
}setImmediate is the right tool here: it lets the poll phase run (so pending requests are handled) before continuing.
Beware recursive nextTick
Because the nextTick queue is drained completely before moving on, code that keeps scheduling more nextTick callbacks starves the loop — I/O never gets a turn:
function forever() {
process.nextTick(forever); // ✗ the server stops responding
}process.nextTick is mainly for library authors who need a callback to run after the current function returns but before anything else. In application code, prefer promises or setImmediate.
Summary of “soon”
| Scheduled with | Runs |
|---|---|
| Synchronous code | now |
process.nextTick(fn) |
after the current operation, before promises |
Promise.then, await, queueMicrotask |
after nextTick, before the loop continues |
setImmediate(fn) |
in the check phase, after I/O polling |
setTimeout(fn, 0) |
in the next timers phase |
| I/O callbacks | in the poll phase, when the operation completes |
In everyday code,
async/awaithides all of this — and that’s fine. Reach for this knowledge when ordering surprises you, or when long-running work needs to share the loop.
Predict the order
Write down the order in which this script prints its letters, then run it to check. Explain why D comes before C.
import { readFile } from 'node:fs';
console.log('A');
setTimeout(() => console.log('B'), 0);
setImmediate(() => console.log('C'));
Promise.resolve().then(() => console.log('D'));
process.nextTick(() => console.log('E'));
readFile(import.meta.filename, () => {
setTimeout(() => console.log('F'), 0);
setImmediate(() => console.log('G'));
});
console.log('H');// A H D E B C G F
//
// A, H — synchronous code first
// D, E — microtasks. In an ES module the top-level code itself runs
// inside a promise job, so promise callbacks (D) drain before the
// nextTick queue (E). In a CommonJS file you'd see E before D.
// B, C — timers phase, then check phase (B/C order can vary at start-up)
// G, F — inside an I/O callback, setImmediate always beats setTimeout(0)
//
// D comes before C because microtasks are drained before the loop
// moves on, and setImmediate runs in the later "check" phase.Summary
- The event loop runs callbacks in phases: timers, pending callbacks, poll (I/O), check (
setImmediate) and close callbacks. - After each callback, Node drains the
process.nextTickqueue, then promise microtasks. - Inside an I/O callback,
setImmediatealways runs beforesetTimeout(fn, 0). - Node exits when no timers, I/O or other work remain.
- Prefer promises and
setImmediate; recursivenextTickcan starve I/O.