Event Loop Deep Dive — Node.js

JavaScript in Node has one call stack (the list of functions that are running), so synchronous code runs to the end first. Then the process.nextTick queue (a…

setTimeout(fn, 0) sounds like it means "run this right now". It doesn't. A callback with a 0 ms delay still runs later than the callback in a Promise.resolve().then(...) written after it.

What decides who goes first is the event loop: the cycle that picks which code runs next, every time JavaScript in Node finishes something. It works like a post office with one clerk. The clerk always finishes with the person in front of them first. Then they handle the pile of small urgent memos until the pile is empty. Only then do they go to the trays, in a fixed order: the "alarm" tray (timers), the "parcel arrived" tray (I/O), the "after the parcels" tray (setImmediate), then the "closing" tray. Each time they finish one item from a tray, they empty the memo pile again. In Node, the clerk is JavaScript, and the person in front of them is the code that is running. The urgent memos are called microtasks, for example a .then callback of a Promise.

One call stack, synchronous code first

JavaScript in Node has one call stack: the list of functions that are running right now. So JavaScript does only one thing at a time. Synchronous code (the lines of your file that run right away, one by one) runs to the end first. Callbacks scheduled for later (timers, Promises, I/O) never interrupt it. They wait in a queue, and the event loop only takes them when the call stack is empty.

Microtasks first, then timers

This code prints four letters. The result is below the code:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
A
D
C
B

A and D are printed by synchronous code, so they come first. The .then callback goes into the microtask queue. This queue holds the code that runs after a Promise finishes (.then, .catch, and the rest of a function after await), and also callbacks passed to queueMicrotask(fn). The microtask queue is emptied completely before the event loop moves on to its next phase (one part of its cycle), including before any timer. So C is printed before B, even though the timer's delay is 0 ms.

Inside the microtask queue, the order is the order of scheduling: first in, first out. Now take a guess. Some code does these five things, in this order. What order comes out?

  1. prints "1 sync",
  2. schedules a 0 ms timer that prints "4 timer",
  3. schedules a queueMicrotask that prints "2 microtask",
  4. schedules a Promise.resolve().then that prints "3 promise",
  5. prints "1b sync".

The answer: 1 sync and 1b sync come first, because they are synchronous. Then 2 microtask, because it was scheduled before 3 promise. Last, 4 timer.

The phases of Node's event loop

Node uses libuv, a library (ready-made code) written in C that runs the event loop and handles I/O. One turn of the event loop goes through these phases, in order:

Phase What runs there
timers setTimeout and setInterval callbacks whose time has come
pending callbacks some system error callbacks deferred from the previous turn
poll I/O callbacks: a file finished reading, data or a new connection arrived. With nothing else to do, Node waits here
check setImmediate callbacks
close callbacks closing callbacks, such as socket.on("close")

Each time one callback finishes, Node empties the process.nextTick queue (explained below), then the microtask queue, and only then moves on to the next callback.

Some of Node's built-in heavy jobs are done outside JavaScript by libuv's thread pool: a group of threads (separate workers that can run at the same time), 4 threads by default. Examples: reading files, finding the address of a domain name (dns.lookup), processing a password (crypto.pbkdf2), and compression (zlib). Network connections don't use the thread pool: Node waits for a signal from the operating system. Your own JavaScript still runs on one thread.

process.nextTick and setImmediate

This code adds two schedulers that belong to Node: setImmediate (its callback runs in the check phase) and process.nextTick.

console.log("sync");
setImmediate(() => console.log("setImmediate"));
setTimeout(() => console.log("setTimeout 0"), 0);
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("end sync");

The result in Node 24, in an ordinary app.js file (CommonJS):

sync
end sync
nextTick
promise
setImmediate
setTimeout 0

process.nextTick(fn) has its own queue, processed before the other microtasks. That is why nextTick is printed before promise.

The last two lines are not guaranteed in that order. Node changes a delay of 0 to 1 ms. So in the main code, the setTimeout(fn, 0) callback is only ready if 1 ms has passed when the first turn starts. If not, the timers phase passes without it, and setImmediate in the check phase runs first. When we tried it on Node 24, setImmediate usually came first, but not always. Don't rely on that order.

Inside an I/O callback, for example an fs.readFile callback, the order is certain:

fs.readFile("app.js", () => {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
});

The result is always immediate, then timeout. The readFile callback runs in the poll phase, and the phase after poll is check, where setImmediate lives. The timers phase has already passed, so the timer only runs in the next turn of the loop.

Blocking the event loop

This code sets a 10 ms timer, then keeps JavaScript busy for 300 ms with a while loop:

const start = Date.now();
setTimeout(() => console.log("timer 10 ms ran after " + (Date.now() - start) + " ms"), 10);
const t = Date.now();
while (Date.now() - t < 300) {} // 300 ms of synchronous work

The output is timer 10 ms ran after 301 ms, not after 10 ms. While that synchronous loop runs, the event loop can't turn, so timers, I/O and every other request wait. The same happens when a process.nextTick callback or a microtask keeps scheduling itself. Its queue never empties, so timers never get their turn. This is called starvation. Heavy calculation for the CPU (the processor) belongs in Worker Threads, covered in a later lesson.

In the exercise: prove the order

In the exercise, the starter already prints 1 sync and 1b sync. Between them, schedule these three things, in this order. Each console.log goes inside its own callback: setTimeout(() => { console.log("4 timer"); }, 0);, then queueMicrotask(() => { console.log("2 microtask"); });, then Promise.resolve().then(() => { console.log("3 promise"); });. The output must be exactly five lines, in this order: 1 sync, 1b sync, 2 microtask, 3 promise, 4 timer.

⚠️ When the order isn't what you expected

TL;DR: JavaScript in Node has one call stack (the list of functions that are running), so synchronous code runs to the end first. Then the process.nextTick queue (a Node scheduler) is emptied, then the microtask queue (the queue for .then, the rest of a function after await, and queueMicrotask) is emptied completely. Only then does the event loop (the cycle that picks the next code) go through its phases: timers, pending callbacks, poll (I/O), check (setImmediate), close. So code that prints A, then B from a 0 ms timer, C from .then, and D, gives A D C B. In the exercise, the order is 1 sync, 1b sync, 2 microtask, 3 promise, 4 timer. The order of setTimeout 0 and setImmediate in the main code isn't guaranteed. Inside an I/O callback, setImmediate always comes first. libuv (a library inside Node) does the I/O outside JavaScript, with its thread pool (4 separate workers). Heavy synchronous code, or a nextTick that keeps repeating, blocks the event loop for every request.

⚡ Synchronous first, microtasks, then timers

Write:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
Guess first: setTimeout and .then both schedule a callback for later. What order is the output in?

A D C B. The synchronous code (A and D) runs to the end first, then the microtasks (the .then callback), and only then the timer, even with a delay of 0.

Meaning: Node has one call stack (the list of functions that are running), so synchronous code finishes first. Then the microtask queue (the queue for Promise callbacks such as .then) is emptied. Only then does the event loop, the cycle that picks the next code, go to the next phase (part of the cycle), such as timers for setTimeout callbacks.

⚡ nextTick goes first

Write:

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

Meaning: process.nextTick(fn) is a scheduler that belongs to Node. In an ordinary CommonJS file, its queue is processed before the other microtasks, such as .then callbacks. So nextTick prints before promise, even though it's written after it.

⚡ Synchronous work blocks everything

Write:

const start = Date.now();
setTimeout(() => console.log("timer 10 ms ran after " + (Date.now() - start) + " ms"), 10);
const t = Date.now();
while (Date.now() - t < 300) {} // 300 ms of synchronous work

Meaning: The output is timer 10 ms ran after 301 ms. While the 300 ms while loop runs, the event loop can't turn, so timers, I/O and every other request wait.

What you will learn