Node's Event Loop Phases
Node's event loop cycles through distinct phases (timers, poll, check, and others), each handling a specific callback category — microtasks still drain between every phase.
Purpose
Node’s event loop layers a phase structure on top of the same microtask-first principle covered in The Event Loop — each phase handles a specific category of callback, cycling in a fixed order.
The phases (selected)
- timers: runs
setTimeout/setIntervalcallbacks whose delay has elapsed. - poll: handles I/O callbacks (file, network); the loop mostly waits here for new events.
- check: runs
setImmediatecallbacks, immediately after the poll phase. - close callbacks: handles things like
socket.on('close', …).
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// Order between these two is NOT guaranteed at the top level.
const fs = require('node:fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout (inside I/O)'), 0);
setImmediate(() => console.log('immediate (inside I/O)'));
// Inside an I/O callback, "immediate" is ALWAYS logged first —
// the poll phase transitions directly into the check phase.
});
Behavior notes
- Microtasks (
Promisecontinuations) drain completely between every phase transition — not just once per full loop cycle. - The relative order of
setTimeout(fn, 0)andsetImmediate(fn)is unspecified when called from the top level, but deterministic (setImmediatefirst) when called from inside an I/O callback. - This phase structure has no direct browser equivalent — the browser’s event loop is simpler, without Node’s I/O-driven phase distinctions.
Common mistakes
- Writing code that depends on the unspecified top-level ordering between
setTimeout(fn, 0)andsetImmediate. - Assuming Node and browser event loop behavior are identical in every detail — the shared microtask-first principle holds, but the phase structure around it is Node-specific.
Runtime notes
Node-specific; the browser has its own, simpler event loop model without these named phases.