The Node.js event loop

Topic 4 of 5 in The Node runtime7 min readIntermediateFree course

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.

The event loop cycles through five phases: timers (setTimeout, setInterval), pending callbacks (some system errors), poll (new I/O for files and sockets), check (setImmediate) and close callbacks (such as socket close). Between every callback, Node drains the process.nextTick queue and then promise microtasks. The poll phase waits for I/O when nothing else is due.

  1. timers — callbacks from setTimeout and setInterval whose time has come.
  2. pending callbacks — a few system-level callbacks deferred from the previous turn.
  3. 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.
  4. check — callbacks scheduled with setImmediate.
  5. 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:

  1. The process.nextTick queue.
  2. The promise microtask queue (.then callbacks, code after await, queueMicrotask).
JavaScript
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 timeout

Both 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.nextTick callbacks. 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:

JavaScript
import { readFile } from 'node:fs';

readFile(import.meta.filename, () => {
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
});
// immediate
// timeout   — always in this order

When 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():

JavaScript
const timer = setInterval(sendMetrics, 10_000);
timer.unref(); // don't keep running just for this

Practical 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:

JavaScript
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:

JavaScript
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/await hides 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.

Exercise

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.

JavaScript
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');

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.nextTick queue, then promise microtasks.
  • Inside an I/O callback, setImmediate always runs before setTimeout(fn, 0).
  • Node exits when no timers, I/O or other work remain.
  • Prefer promises and setImmediate; recursive nextTick can starve I/O.