Skip to content
jshacks.dev
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.

The Node.js event loop is the mechanism that lets one thread run your JavaScript while many operations wait in the background. When something finishes, such as a timer, a file read or an incoming connection, the loop picks up its callback and runs it. The loop is not one queue but a sequence of phases, each with its own queue of callbacks, and knowing the order explains behaviour that otherwise looks random: why setImmediate can run before setTimeout(fn, 0), why process.nextTick jumps ahead of promises and why a tight chain of microtasks can starve I/O. This post walks through the phases on Node.js 24, with samples whose output you can predict from the rules.

For the bigger picture of how V8 and libuv fit together, see Node.js architecture: V8, libuv and the event loop explained. This post zooms in on the loop itself.

The phases in order

Each turn of the loop, called a tick, passes through these phases:

  1. Timers. Runs callbacks from setTimeout and setInterval whose time has elapsed.

  2. Pending callbacks. Runs some system-level callbacks deferred from the previous tick, such as certain network errors.

  3. Idle and prepare. Used internally by Node.js.

  4. Poll. Retrieves new I/O events and runs their callbacks. If nothing else is scheduled, the loop may wait here for events.

  5. Check. Runs setImmediate callbacks.

  6. Close callbacks. Runs callbacks for closed resources, such as a socket's close event.

Two other queues sit outside the phases. The process.nextTick queue and the promise microtask queue run between callbacks: after the current operation completes and after each callback in any phase, Node.js drains the nextTick queue first and then the microtasks, and repeats until both are empty.

The synchronous part comes first

Your script's top-level code runs to completion before the loop starts at all. Only then does the loop begin its first tick. That is why a console.log after a setTimeout still prints first.

order.cjsJavaScript
console.log("sync start");

process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
queueMicrotask(() => console.log("microtask"));

console.log("sync end");
Text
sync start
sync end
nextTick
promise
microtask

This file is CommonJS. The two console.log calls run as part of the script. When the script finishes, Node.js drains the nextTick queue, so nextTick comes next, and then the microtask queue, which holds the promise callback and the queueMicrotask callback in the order they were queued.

An ES module differs. Its evaluation is itself run from a promise job, so when the same code is saved as .mjs, the microtask queue is already being drained when the module body finishes, and the promise and microtask callbacks run before nextTick. Do not depend on the order between nextTick and promises at the top level of a file. Inside callbacks, the rule is reliable: the nextTick queue runs first, then promises.

Timers against immediates

setTimeout(fn, 0) schedules a callback for the timers phase of a future tick, after at least one millisecond, since Node.js treats a zero delay as one. setImmediate(fn) schedules it for the check phase of the current tick, after poll. From the main module, which of them runs first depends on how long the process took to start, so the order is not guaranteed.

Inside an I/O callback, the order is fixed. You are in the poll phase, the next phase is check, and the timers phase only comes round on the next tick.

io.mjsJavaScript
import { readFile } from "node:fs";

readFile(import.meta.filename, () => {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
});
Text
immediate
timeout

The file read callback runs in the poll phase. The loop moves on to check, which runs the immediate, and only after closing and wrapping around does it reach timers, which runs the timeout. Whenever you need "run this after the current I/O, before timers", setImmediate is the tool.

nextTick and microtasks between phases

The nextTick and microtask queues run after each callback, not once per tick. A callback that schedules a nextTick sees it run before the loop moves to the next callback in the same phase.

between.mjsJavaScript
import { readFile } from "node:fs";

readFile(import.meta.filename, () => {
  setImmediate(() => console.log("immediate 1"));
  setImmediate(() => {
    console.log("immediate 2");
    process.nextTick(() => console.log("nextTick inside immediate 2"));
  });
  setImmediate(() => console.log("immediate 3"));
});
Text
immediate 1
immediate 2
nextTick inside immediate 2
immediate 3

The nextTick scheduled by the second immediate runs as soon as that callback ends, before the third immediate. Since Node.js 11, this is the behaviour for timers and immediates too: the queues drain between individual callbacks, matching browsers.

Why starvation happens

Because both queues drain completely before the loop continues, a callback that keeps scheduling more of them never lets the loop advance.

starve.mjsJavaScript
let count = 0;

function loop() {
  count += 1;
  if (count < 1_000_000) {
    Promise.resolve().then(loop);
  } else {
    console.log("microtasks finished", count);
  }
}

setTimeout(() => console.log("timer fired"), 0);
loop();
Text
microtasks finished 1000000
timer fired

The timer was due almost at once, but the loop never reached the timers phase until a million microtasks were done. With process.nextTick the effect is even stronger, since its queue is drained before promises. A recursive nextTick with no end blocks I/O completely, which is why the documentation recommends setImmediate for splitting up long work: it yields to the loop between chunks.

Splitting long work with setImmediate

Because setImmediate yields to the loop, it lets several long jobs share the thread by taking turns.

chunks.mjsJavaScript
function work(name, chunks) {
  let done = 0;
  function step() {
    done += 1;
    console.log(`${name} chunk ${done}`);
    if (done < chunks) setImmediate(step);
  }
  step();
}

work("A", 3);
work("B", 3);
Text
A chunk 1
B chunk 1
A chunk 2
B chunk 2
A chunk 3
B chunk 3

Each job does one chunk and then schedules the next with setImmediate. The immediates queued during one tick run in the next, so the two jobs alternate. Without the yield, job A would run all three chunks before B started, and in a real server, the requests waiting behind a long job would wait for all of it. In practice each chunk would process a few hundred items, and the gaps between them are where incoming connections, timers and other I/O get their turn.

What the poll phase does

Poll has two jobs: calculating how long it should block waiting for I/O, and running the I/O callbacks. If there are setImmediate callbacks scheduled, poll does not wait and the loop proceeds to check. If there are timers, poll waits no longer than the nearest one is due. If there is nothing at all to wait for, the loop exits and the process ends. That last point is why a script with no pending timers, servers or handles finishes by itself.

You can see the "nothing left" rule at work with a timer that you unreference.

unref.mjsJavaScript
const timer = setInterval(() => console.log("tick"), 1000);
timer.unref();
console.log("done");
Text
done

The interval would tick forever, but unref tells the loop not to count it as work that keeps the process alive, so the process exits straight after the last line.

A practical rule of thumb

Think of the order in four levels, from highest to lowest priority. First the code that is running now. Then process.nextTick callbacks. Then promise and queueMicrotask callbacks. Then the next phase of the loop. Use setImmediate to run something after current I/O and let the loop breathe. Use setTimeout for a real delay. Use a promise for ordinary asynchronous continuation. Avoid process.nextTick unless you specifically need to run before the loop continues, such as emitting an event after a constructor returns so the caller can attach a listener.

Also inAsync
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.