---
title: "The Node.js Event Loop Explained with Examples"
description: "The phases of the Node.js event loop, microtasks versus macrotasks, process.nextTick and setImmediate, and how to find code that blocks the loop."
url: https://sanderyaz.com/en/blog/nodejs-event-loop-explained/
author: Sander Yazıcıoğlu
date: 2026-12-02
updated: 2026-12-02
lang: en
tags: ["Node.js","JavaScript","Backend","Performance"]
---

# The Node.js Event Loop Explained with Examples

Node.js runs JavaScript on a single thread yet handles thousands of concurrent connections. The secret is the **event loop**. Beyond being a classic interview question, understanding it is also the answer to "why did the server suddenly slow down?" in production.

## The core idea

Node.js hands slow work such as file reads, network requests and timers to the operating system or libuv's thread pool. When that work finishes, its callback goes into a queue. The event loop drains these queues in order and runs your JavaScript. While your JavaScript runs, **no other callback can run**.

## The phases

Each turn of the loop goes through these phases:

| Phase | What runs |
|---|---|
| timers | Expired `setTimeout` and `setInterval` callbacks |
| pending callbacks | Deferred callbacks for some system errors |
| poll | I/O events (network, files); waits here if nothing is pending |
| check | `setImmediate` callbacks |
| close callbacks | Close events such as `socket.on('close')` |

Between phases, and after every callback, the **microtask** queues are drained.

## Microtasks and macrotasks

```js
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
```

Output:

```text
sync
nextTick
promise
timeout
immediate
```

- Synchronous code finishes first.
- The `process.nextTick` queue drains even before the promise queue.
- Then promise callbacks (microtasks) run.
- The order of `setTimeout(0)` and `setImmediate` isn't guaranteed in the main module, but inside an I/O callback `setImmediate` always runs first.

## Blocking the loop

If a request runs a synchronous loop that takes 200 ms, **every user on the server** waits those 200 ms. Usual suspects:

- `JSON.parse` / `JSON.stringify` on large payloads.
- Synchronous APIs such as `fs.readFileSync`.
- Complex regular expressions (especially patterns with catastrophic backtracking).
- CPU-heavy work: hashing, compression, image processing.

## Detecting it

Node.js ships a built-in tool for measuring loop delay:

```js
import { monitorEventLoopDelay } from 'node:perf_hooks';

const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();

setInterval(() => {
  console.log('p99 loop delay (ms):', histogram.percentile(99) / 1e6);
  histogram.reset();
}, 10000);
```

If p99 delay regularly exceeds tens of milliseconds, something is blocking. Profile with `node --cpu-prof` to see which function burns the time.

## Fixes

- **Use async APIs:** `fs.promises`, streams.
- **Chunk big work:** split the loop and yield with `setImmediate` between chunks.
- **Move CPU-heavy work out:** worker threads or a separate service or queue.
- **Stream large data:** process a file or HTTP body piece by piece instead of loading it all into memory.

## Why it matters for realtime systems

In WebSocket servers loop delay hits users directly: messages go out late, heartbeats are missed and connections drop. Add loop delay to the metrics described in [realtime systems with Node.js and WebSocket](/en/blog/websocket-realtime-nodejs/).

## Conclusion

Understanding the event loop is the foundation of fast Node.js code: keep synchronous work short, know the microtask order, measure the delay, and move CPU-heavy work off the main thread.

---

About the author: [Sander Yazıcıoğlu](https://sanderyaz.com/en/about/). Sander Yazıcıoğlu is a Senior Full-Stack Developer in Istanbul. At LiveTesting he builds the backend, frontend, realtime systems and Appium automation of a real-device testing platform; before that he built enterprise Angular apps at Testinium and Loadium.
