Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 133 ยท The Runtime

The Event Loop

Understand the Node.js event loop - phases, microtasks versus macrotasks, nextTick, setImmediate and setTimeout order, starving the loop and measuring lag.

Node.js runs your JavaScript on a single thread, yet a Node server can juggle thousands of connections. The trick is the event loop: a never-ending cycle that waits for things to happen (a timer expiring, a file being read, a network packet arriving) and then runs the matching piece of your code. Your code never waits; it hands work to the system, says "call me back when it is done", and returns.

Understanding the loop explains behaviours that otherwise look like magic or bugs: why setTimeout(fn, 0) does not run immediately, why a promise callback runs before a timer, why one slow function freezes an entire server, and why process.nextTick can cause trouble. This lesson is about the order in which things run, which you can verify yourself in the examples below. If you have not yet read How Node.js Works, a skim helps; for timer details continue afterwards with Timers.

One thread, many waiting jobs

When your program starts, Node runs your main file from top to bottom. That is ordinary, synchronous code, and while it runs nothing else can happen. When it finishes, Node enters the event loop, which keeps going as long as there is something left to wait for: an open timer, a listening server, a pending file read. When nothing is left, the process exits on its own.

The slow work itself is not done by your JavaScript thread. Network sockets are handled by the operating system's notification mechanism; file system calls and some crypto and DNS work run on a small pool of helper threads (four by default). When one of them finishes, the result is queued, and the event loop picks it up and runs your callback on the main thread. Only your callbacks share the single thread, so two of them never run at the same moment.

The phases of one loop turn

Each trip around the loop is called a tick (not to be confused with process.nextTick). A tick moves through fixed phases, each with its own queue of callbacks:

  1. Timers. Runs callbacks of setTimeout and setInterval whose time has come.
  2. Pending callbacks. Runs a few deferred system callbacks, such as certain TCP errors.
  3. Idle, prepare. Internal use only.
  4. Poll. Retrieves new I/O events and runs their callbacks (file reads finishing, data arriving on a socket). If there is nothing else to do, the loop may wait here for I/O, but never past the next timer's due time.
  5. Check. Runs setImmediate callbacks.
  6. Close callbacks. Runs 'close' handlers, for example when a socket is destroyed.

Between every callback (and between phases), Node drains two special queues before moving on: first the process.nextTick queue, then the microtask queue holding promise reactions and queueMicrotask callbacks. Timers, I/O callbacks and setImmediate callbacks are called macrotasks; microtasks always jump ahead of the next macrotask.

TEXT
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”Œโ”€โ”€โ”€>โ”‚    timers    โ”‚   setTimeout / setInterval callbacks
   โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚    โ”‚   pending    โ”‚
   โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”        incoming connections, data
   โ”‚    โ”‚     poll     โ”‚<โ”€โ”€โ”€โ”€โ”€ file reads, network I/O callbacks
   โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚    โ”‚    check     โ”‚   setImmediate callbacks
   โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ””โ”€โ”€โ”€โ”€โ”ค    close     โ”‚   'close' event callbacks
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   after EVERY callback: nextTick queue, then promise microtasks

Synchronous code first, then microtasks

The simplest ordering rule: all the synchronous code of the current script runs to completion before any callback. After that, microtasks run, then the loop proceeds to timers and I/O.

Node.js Synchronous code, microtasks and a timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice what happened. Lines 1 and 2 print first because the script finishes before anything else runs. The timer, even with a delay of zero, waits for a later turn of the loop, so it prints last. The three "run soon" callbacks all run before it.

You may have read that nextTick always runs before promises. That is true in CommonJS but not in an ES module like this one. An ES module is itself evaluated inside a promise job, so when the script ends Node is already in the microtask queue and finishes it before it looks at the nextTick queue. Run the same code as CommonJS and the order of nextTick and the promise swaps.

Node.js The same code as CommonJS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Here nextTick wins. The practical advice: never write code that depends on the relative order of nextTick and promise callbacks. Rely only on the firm rules: synchronous code first, then nextTick and microtasks, then macrotasks.

Microtasks queued by a microtask run in the same drain, before the loop continues. A promise .then that schedules another promise .then still finishes before the next timer or I/O callback.

setTimeout versus setImmediate

setImmediate(fn) means "run this in the check phase of the current loop turn", right after the poll phase. setTimeout(fn, 0) means "run this in the timers phase once at least one millisecond has passed". Which runs first?

From the main script, it depends: if the loop starts up in less than a millisecond, setImmediate wins; otherwise the timer does. The order can change between runs on the same machine, so never rely on it.

Inside an I/O callback, though, the answer is fixed. The loop is in the poll phase, the next phase is check, and the timers phase only comes after a full lap. So setImmediate always runs first.

Node.js Inside an I/O callback, setImmediate always wins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Expect callback body done, then nextTick and promise (the two microtask kinds, drained as soon as the callback returns), then immediate, and only then timeout 0. This is the one setTimeout/setImmediate comparison that is guaranteed.

A good mental model for choosing between them: use setImmediate to "let pending I/O happen, then continue", and process.nextTick only for rare cases where you must run something before anything else, such as emitting an event after a constructor returns so the caller has time to attach listeners.

Starving the event loop

Because microtasks and nextTick callbacks run to exhaustion before the loop continues, code that keeps adding more of them can starve timers and I/O. They never get a turn.

This demo is deliberately bounded (one thousand microtasks), so it finishes. Replace the limit with Infinity and the timer would never fire and the program would hang.

Node.js A chain of promise callbacks delays a ready timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The timer was due almost immediately, but all one thousand chained microtasks ran first. The same trap exists with process.nextTick, and Node documents it as the reason to prefer setImmediate for recursive scheduling: a recursive setImmediate yields to the loop between each call, so I/O keeps flowing.

Blocking the loop

The most common event-loop problem is not starvation by microtasks but plain blocking: a synchronous function that takes a long time. While it runs, no timer fires, no request is answered, and no callback runs. On a server, one slow function stalls every client.

Node.js A busy loop delays a timer that was due earlier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The timer's callback is queued, but it is a macrotask and the main thread was occupied, so it had to wait until the synchronous code finished. (We print booleans instead of raw timings, because exact milliseconds vary from run to run.) Real-life versions of this busy loop are JSON.parse of a huge file, a regular expression with catastrophic backtracking, fs.readFileSync in a request handler, a long for loop over a million records, or synchronous cryptography.

Ways out:

  • Use the asynchronous API whenever one exists (fs.readFile instead of readFileSync in server code).
  • Split the work into chunks and yield between them with setImmediate, so other callbacks can run.
  • Move CPU-heavy work to another thread with worker threads or another process.

Chunking work with setImmediate

Node.js Processing a big list without freezing the loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four chunks of at most three items each run on separate turns of the loop. The two unrelated callbacks were queued before the second chunk, so they run in between; on a real server that gap is where timers and incoming requests get handled. With a million items and a chunk size in the thousands, a server stays responsive while a big task runs in the background.

Measuring event-loop lag

Event-loop lag is how late callbacks run compared with when they were due. It is the best single health indicator for a Node service: if it climbs, something is blocking. You can measure it yourself by scheduling a timer and checking how late it fires, or use the built-in histogram from perf_hooks.

Node.js A lag probe and the built-in delay histogram

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The probe reports lag as a plain number you could log or export to a monitoring system. In production you would sample a histogram periodically and alert on its 99th percentile (histogram.percentile(99), in nanoseconds). We will return to this in Measuring Performance.

What happens when you await

await is built on promises, so it uses the microtask queue. Code after an await runs as a microtask once the awaited promise settles, which means it jumps ahead of timers that are already due.

Node.js await resumes as a microtask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You get work: before await, main: after calling work(), work: after await, timer. An async function runs synchronously until its first await, then hands control back. See async/await Patterns for the practical consequences.

Common misunderstandings

  • "Node is single-threaded, so it can only do one thing at a time." Your JavaScript does one thing at a time; the waiting happens elsewhere, in parallel.
  • "setTimeout(fn, 0) runs right away." It runs in a later loop turn, after all microtasks. And the delay is a minimum, never a promise.
  • "A promise makes work run in the background." A promise only organises the result. The executor function and any synchronous work inside then still run on the main thread and still block it.
  • "async functions are asynchronous because of the keyword." They run synchronously until the first await. A heavy for loop inside an async function blocks just as before.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order do these run after the script's synchronous code finishes: a promise .then callback, a setTimeout(fn, 0) callback?

    Microtasks (promise reactions, queueMicrotask) are drained after the current operation, before the loop moves to the timers phase.
  2. 2. Inside an fs.readFile callback you schedule both setTimeout(fn, 0) and setImmediate(fn). Which runs first?

    The callback runs in the poll phase, and the check phase (setImmediate) comes next. The timers phase only returns after a full lap.
  3. 3. What happens to the event loop if a synchronous function runs for two seconds?

    JavaScript runs on one thread and a callback cannot interrupt running code, so every other callback waits.
  4. 4. Why can endlessly rescheduling work with process.nextTick or queueMicrotask freeze a server?

    The nextTick and microtask queues run until empty. If each callback adds another, the loop never advances to other phases.
  5. 5. Which is a good way to process a huge array without freezing a server?

    Promises and async do not move work off the main thread. Yielding with setImmediate (or using a worker thread) lets other callbacks run.

Summary

  • Node runs your JavaScript on one thread; the event loop picks up finished work and runs the matching callbacks one at a time.
  • A loop turn goes through timers, pending, poll, check (setImmediate) and close phases.
  • Synchronous code runs first, then nextTick and microtasks (promises, queueMicrotask, code after await), then macrotasks (timers, I/O, setImmediate).
  • In ES modules promise callbacks run before nextTick; in CommonJS it is the other way round, so do not depend on it.
  • setTimeout(0) versus setImmediate from the main script is unspecified; inside an I/O callback setImmediate always wins.
  • Long synchronous work and endless microtask chains block or starve the loop; chunk the work, use async APIs or move CPU work to worker threads.
  • Measure loop lag with a timer probe or monitorEventLoopDelay and alert when it grows.

Next: Timers