← All articles
Languages & Runtimes

How Node.js Works: The Event Loop

Two rules that let you predict the order of setTimeout, setImmediate, process.nextTick and Promise callbacks in Node.js, with code you can run to check each one.

The Node.js event loop decides which of your callbacks runs next. It follows two rules, and once you know them you can predict the order of setTimeout, setImmediate, process.nextTick and Promise callbacks. This guide follows the official guide, The Node.js Event Loop, and describes Node.js 20 and later.

Three callbacks that print in reverse order

Save this as order.js, and read it before you run it.

console.log('start');

setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));

console.log('end');

Predict the five lines of output, then run node order.js.

start
end
nextTick
promise
timeout

The three scheduled callbacks print in the reverse of the order you wrote them. The timer has a delay of 0, and it still prints last. Two rules explain this output.

If your output differs: Save the file with a .js extension, in a folder whose package.json does not set "type": "module". That setting, or a .mjs extension, makes the file an ES module, and there promise prints before nextTick. Every example in this guide uses the require style, which Node.js calls CommonJS.

Rule 1: when your code returns, Node.js empties two queues

Node.js runs one piece of your JavaScript at a time, and that piece runs until it returns. In order.js the first piece is the file itself, so start and end print first.

While the file ran, process.nextTick() and .then() each stored a callback for later. Node.js keeps two queues for these callbacks:

  • The nextTick queue holds callbacks passed to process.nextTick().
  • The microtask queue holds Promise callbacks: .then(), .catch(), .finally() and the code after an await. Callbacks passed to queueMicrotask() wait there too.

When the running code returns, Node.js runs every callback in the nextTick queue, then every callback in the microtask queue. It looks for other work, such as a timer that is due, only when both queues are empty.

Here is order.js again, step by step:

  1. The file runs from top to bottom. It prints start and end, and it stores three callbacks.
  2. The file returns, so Node.js empties the nextTick queue, which prints nextTick.
  3. Node.js empties the microtask queue, which prints promise.
  4. Both queues are empty, so Node.js runs the timer callback, which prints timeout.

Rule 1 applies again after every callback Node.js runs, whether it came from a timer, a file read or a network request.

A queue counts as empty only when the callbacks added during the emptying have run too. After the microtask queue is empty, Node.js checks the nextTick queue again, and it repeats this until both are empty. The nested example later in this guide tests that.

Rule 1: After the main file and after every callback, Node.js runs all nextTick callbacks, then all Promise callbacks, before anything else.

Rule 2: the event loop visits three queues in a fixed order

Which runs first: a timer, a finished file read or a setImmediate() callback? Rule 1 does not say, and this example has all three.

const fs = require('node:fs');

fs.readFile(__filename, () => {
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
});

Predict which line prints first, then run it.

immediate
timeout

It prints in this order on every run, and the reason is where each callback waits. Callbacks that come from outside your running code wait in separate queues, one queue per kind. The event loop visits these queues one after another, always in the same order. A phase is one visit to one queue.

Three phases matter for the code you write:

Order Phase Callbacks it runs
1 timers setTimeout() and setInterval() callbacks whose delay has passed
2 poll Callbacks for finished I/O, such as a file that was read or a request that arrived
3 check setImmediate() callbacks

After check, the loop goes back to timers.

        your main file runs first
                   │
                   v
           ┌───────────────┐
   ┌──────>│    timers     │  setTimeout, setInterval
   │       └───────┬───────┘
   │               v
   │       ┌───────────────┐
   │       │     poll      │  finished I/O; the loop waits here when idle
   │       └───────┬───────┘
   │               v
   │       ┌───────────────┐
   │       │     check     │  setImmediate
   │       └───────┬───────┘
   │               │
   └───────────────┘

   Rule 1 applies after the main file and after every callback in every phase.

Notice that check comes directly after poll, and that timers come after check. That explains the example:

  1. The readFile callback is an I/O callback, so it runs in the poll phase. It schedules a timer callback and a setImmediate() callback.
  2. The next phase after poll is check, so immediate prints.
  3. The loop goes back to timers. When the timer is due, its callback prints timeout.

Rule 2: The loop runs timers that are due, then finished I/O, then setImmediate() callbacks, and then starts again at timers.

Node.js hands slow work, such as a file read, to the operating system or to a background thread. The callback joins the poll queue when the work finishes, so your JavaScript never waits for it. When no callback is ready, the loop waits in the poll phase, but no longer than the time until the next timer is due.

The full route has three more phases: pending callbacks, idle and prepare, and close callbacks. They handle some system errors, internal work and some 'close' events, and the official guide describes each one.

From the main file, the order can change. Run the same two calls without readFile, and on some runs timeout prints first. Node.js turns a delay of 0 into 1 ms. The loop starts at timers, and whether 1 ms has passed by then depends on your machine.

A nested example that tests both rules

Predict the ten lines of output before you run this.

setImmediate(() => {
  console.log('immediate A');
  process.nextTick(() => console.log('nextTick inside A'));
  Promise.resolve().then(() => console.log('promise inside A'));
});

setImmediate(() => console.log('immediate B'));

process.nextTick(() => {
  console.log('nextTick 1');
  Promise.resolve().then(() => console.log('promise from nextTick 1'));
  process.nextTick(() => console.log('nextTick 2'));
});

Promise.resolve().then(() => {
  console.log('promise 1');
  process.nextTick(() => console.log('nextTick from promise 1'));
});

console.log('sync');

Output, the same on every run:

sync
nextTick 1
nextTick 2
promise 1
promise from nextTick 1
nextTick from promise 1
immediate A
nextTick inside A
promise inside A
immediate B

The first six lines come from Rule 1, and the last four come from Rule 2 with Rule 1 inside it.

  1. sync: the main file runs. It stores two setImmediate() callbacks, one nextTick callback and one Promise callback.
  2. nextTick 1, nextTick 2: Rule 1 starts with the nextTick queue. nextTick 1 adds nextTick 2 to that queue, so nextTick 2 runs before Node.js moves on.
  3. promise 1, promise from nextTick 1: the microtask queue runs next, in the order the callbacks were added.
  4. nextTick from promise 1: promise 1 added this callback. Node.js finds it when it checks the nextTick queue again.
  5. immediate A: both queues are empty, so the loop starts. No timer and no I/O is waiting, so the loop reaches check.
  6. nextTick inside A, promise inside A: Rule 1 applies when A returns, before B runs.
  7. immediate B: the check phase continues with its next callback.

The cost: one slow callback delays every other callback

Because one piece of JavaScript runs at a time, the loop cannot move while your code is running. Run this to see it.

const start = Date.now();

setTimeout(() => {
  console.log(`timer ran after ${Date.now() - start} ms`);
}, 100);

// slow synchronous work
while (Date.now() - start < 300) {}

Output (your number may be a few milliseconds higher):

timer ran after 300 ms

The timer was due at 100 ms, but the loop could not reach the timers phase until the main file returned. A delay of 100 does not mean “run in 100 ms”. It means “run no earlier than 100 ms”, and the real wait is that delay plus whatever your code is doing.

Blocking is one callback keeping the loop from moving, so that no other callback can run. In a server, every other request waits for that callback, including requests that need almost no work. Common causes are a large JSON.parse(), a long loop, and a *Sync function such as fs.readFileSync() inside a request handler. The official guide Don’t Block the Event Loop covers these cases.

Rule: No other callback runs while one callback runs, so keep every callback short.

A nextTick callback that schedules itself stops the loop

Rule 1 has the same cost. The loop cannot move until the nextTick queue is empty, and this callback keeps adding to it.

const start = Date.now();
let count = 0;

setTimeout(() => {
  console.log(`timer ran after ${Date.now() - start} ms, count = ${count}`);
}, 0);

function again() {
  count++;
  if (count < 100_000) process.nextTick(again);
  else console.log(`again finished after ${Date.now() - start} ms`);
}
again();

Output (the times depend on your machine):

again finished after 13 ms
timer ran after 15 ms, count = 100000

The timer was due after 1 ms, and it ran only after all 100,000 nextTick callbacks. Without the count < 100_000 limit, the timer would never run, and no I/O callback would run. A Promise callback that schedules itself has the same effect. The official guide calls this starving the loop, because the other callbacks never run.

Now change process.nextTick(again) to setImmediate(again) and run it again.

timer ran after 0 ms, count = 23
again finished after 1333 ms

The timer line shows 0 or 1 ms, and the count changes on every run. A setImmediate() callback scheduled from inside the check phase waits for the next visit to check, so the loop passes timers and poll between two calls to again. The cost is that again needed 1,333 ms here, against 13 ms with process.nextTick(), because the loop goes around once for each call. These numbers come from one run on one machine, and yours will differ.

Rule: A callback that schedules itself uses setImmediate(), and never process.nextTick() or a Promise.

Which call to use

Call When its callback runs Use it for
process.nextTick(fn) After the current code returns, before Promise callbacks One short step that must run before any I/O, such as emitting an event after the caller has attached its listeners
.then(), await, queueMicrotask(fn) After the nextTick queue is empty Ordinary asynchronous code
setTimeout(fn, ms) In the timers phase, once ms has passed A delay or a timeout, where a late callback is acceptable
setImmediate(fn) In the check phase, directly after poll Work that should let I/O and timers run first, such as one part of a long job

The names suggest the opposite of what happens, because process.nextTick() runs sooner than setImmediate(). The official guide says the names should be swapped, and that they will stay because too many npm packages depend on them.

When either call would work, the official guide recommends setImmediate(), because it is easier to reason about.

Next, add a setImmediate() line to order.js and predict where immediate prints. Run it twenty times, then use the note about the main file to explain what you see.

If you want the next guide in this series when it comes out, subscribe to the newsletter.

Comments

No comments yet. Ask a question or share what worked for you.

Leave a comment

Write a comment before you post.

Enter your name.

Never shown on the site.

Enter an email address like name@example.com.

Comments are checked before they appear. Fields marked * are required.

Keep reading

Related articles

  • Languages & Runtimes

    How V8 runs your JavaScript inside Node.js

    How V8 works in Node.js: lazy parsing, bytecode, JIT tiers, hidden classes, inline caches and deopts, with commands you can run on Node.js 22.