Event Loop in JavaScript

JavaScript Event Loop Explained: Concurrency Model Guide

The Single-Threaded Illusion: How JavaScript Handles Concurrency

JavaScript is fundamentally a single-threaded language. It has a single call stack, meaning it can only execute one piece of code at any given instant. Yet, Node.js servers routinely handle tens of thousands of concurrent HTTP requests, and browser applications render smooth 60fps animations while streaming multi-gigabyte video feeds and parsing background network payloads.

How does a single-threaded runtime manage massive asynchronous concurrency without locking up? The answer lies in the Event Loop—an orchestrator built into the browser runtime and the Node.js C++ core (libuv) that continuously delegates operations to the operating system kernel and processes callbacks when the call stack clears.

In this guide, we break down the JavaScript event loop mechanics from the ground up: from the call stack and microtask queues to the 6 internal phases of the libuv event loop in Node.js, complete with execution traces and production concurrency patterns.


Core Architectural Components: Call Stack, Heap, and Queues

To understand the event loop, you must first understand the three distinct memory and execution structures that interact during every JavaScript program:

1. The Call Stack

A LIFO (Last In, First Out) data structure that tracks function execution frames. When a function is called, a frame is pushed onto the stack. When the function returns, its frame is popped off. If a function runs a long synchronous computation, the call stack is blocked, freezing all user interactions and network processing.

2. The Memory Heap

An unstructured region of memory where objects, closures, arrays, and variables are allocated. Memory allocation and deallocation here are managed automatically by the V8 garbage collector (Scavenger and Mark-Sweep-Compact cycles).

3. Background APIs & Queues

When you initiate an asynchronous operation—such as reading a file via fs.readFile, making a fetch() request, or scheduling a timer with setTimeout—the JavaScript engine hands off the task to underlying system APIs (libuv thread pool or OS kernel epoll/kqueue). Once the operation completes, its callback is queued.


Macrotasks vs. Microtasks: The Execution Hierarchy

A common misconception among intermediate developers is that all asynchronous callbacks wait in a single queue. In reality, JavaScript maintains two distinct queue tiers with radically different execution priorities:

Queue TierExamplesExecution Priority
Microtask Queue (Job Queue)Promise.then(), Promise.catch(), queueMicrotask(), MutationObserver, process.nextTick() (Node.js)Highest Priority: Drained completely after every synchronous call stack frame empties, before the next macrotask is allowed to execute.
Macrotask Queue (Task Queue)setTimeout(), setInterval(), setImmediate() (Node.js), I/O callbacks, UI rendering eventsStandard Priority: The event loop executes exactly one macrotask per tick, then pauses to drain all pending microtasks before selecting the next macrotask.

Crucial Rule: The runtime will never pick up the next macrotask from the queue until the microtask queue is 100% empty. If microtasks continuously spawn additional microtasks, the event loop starves, completely blocking I/O and UI rendering.


The 6 Phases of the Node.js Event Loop (libuv)

In browser environments, the event loop simply toggles between tasks, microtasks, and rendering steps. In Node.js, asynchronous execution is managed by the C library libuv, which organizes execution into six strict, sequential phases. Each phase maintains its own FIFO queue of callbacks:

   ┌───────────────────────────┐
┌─>│          timers           │  setTimeout(), setInterval()
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │  TCP errors (ECONNREFUSED), deferred I/O
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │  Internal libuv operations
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           poll            │  Incoming network connections, file I/O
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           check           │  setImmediate() callbacks
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │      close callbacks      │  socket.on('close', ...)
└──┴───────────────────────────┘

1. Timers Phase

The event loop inspects the min-heap of active timers scheduled via setTimeout() and setInterval(). It executes all callbacks whose threshold has elapsed. Keep in mind: timer thresholds represent the minimum delay before execution, not a guaranteed exact timestamp.

2. Pending Callbacks Phase

Executes I/O callbacks deferred from the previous loop iteration. For example, if a TCP socket receives an ECONNREFUSED error while attempting to connect, the OS reports the error and libuv queues the callback here.

3. Idle, Prepare Phase

Used internally by libuv for internal system checks and state synchronization. Developers cannot inject code directly into this phase.

4. Poll Phase

The heart of Node.js I/O concurrency. The poll phase has two primary responsibilities:

  1. Calculating how long it should block and wait for incoming I/O events.
  2. Processing events in the poll queue until the queue is exhausted or the system limit is reached.

If the poll queue is empty, the event loop checks if any setImmediate() callbacks are pending. If yes, it ends the poll phase and proceeds immediately to the Check phase. If no setImmediate() scripts exist, it blocks and waits for new I/O events up to the nearest timer threshold.

5. Check Phase

Dedicated exclusively to executing callbacks registered via setImmediate(). This design allows developers to execute code immediately after the poll phase finishes handling I/O events.

6. Close Callbacks Phase

Handles cleanup and socket termination callbacks, such as socket.on('close', ...) or server.close(). If a handle or stream closes abruptly, its cleanup event is processed here.


The Secret Microtask Queues: process.nextTick vs. Promises

Neither process.nextTick() nor Promise.resolve().then() are part of libuv’s 6 phases. Instead, they run in Node.js as part of the JavaScript layer between phases.

Node.js maintains two separate microtask queues:

  • nextTickQueue: Holds callbacks registered with process.nextTick().
  • microTaskQueue: Holds resolved Promise callbacks (.then(), .catch(), await resumption).

Whenever the JavaScript execution stack finishes, Node.js first flushes the entire nextTickQueue. Only after the nextTickQueue is completely empty does it flush the Promise microTaskQueue. Only after both are empty will the event loop advance to the next libuv phase!


Execution Trace Quiz: Test Your Understanding

Consider the following complex asynchronous script. What order will the console logs appear in?

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

console.log('1: Synchronous start');

setTimeout(() => {
  console.log('2: setTimeout 0ms (Timers Phase)');
}, 0);

setImmediate(() => {
  console.log('3: setImmediate (Check Phase)');
});

Promise.resolve().then(() => {
  console.log('4: Promise Microtask (microTaskQueue)');
});

process.nextTick(() => {
  console.log('5: process.nextTick (nextTickQueue)');
});

fs.readFile(__filename, () => {
  console.log('6: I/O Callback (Poll Phase)');
  
  setTimeout(() => console.log('7: Nested setTimeout'), 0);
  setImmediate(() => console.log('8: Nested setImmediate'));
  process.nextTick(() => console.log('9: Nested nextTick'));
});

console.log('10: Synchronous end');

Step-by-Step Execution Breakdown

  1. Synchronous Code Runs First:
    1: Synchronous start and 10: Synchronous end log immediately to the console. The call stack clears.
  2. Microtask Queues Drain:
    Before advancing to any event loop phase, Node checks microtasks. process.nextTick has priority over Promises:
    → 5: process.nextTick (nextTickQueue)
    → 4: Promise Microtask (microTaskQueue)
  3. Timers vs. Check Phase (Top Level):
    At top-level module scope, whether setTimeout(..., 0) or setImmediate() runs first is non-deterministic because it depends on process startup time and system clock tick alignment. Usually, the 0ms timer fires:
    → 2: setTimeout 0ms (Timers Phase)
    → 3: setImmediate (Check Phase)
  4. Poll Phase (File I/O Finishes):
    The file read completes and its callback executes in the poll phase:
    → 6: I/O Callback (Poll Phase)
  5. Inside the I/O Callback:
    – process.nextTick executes immediately upon call stack exit: 9: Nested nextTick.
    – The event loop is currently in the Poll Phase. When the poll phase finishes, where does it go next? Directly to the Check Phase!
    – Therefore, inside any I/O cycle, setImmediate is guaranteed to run before setTimeout:
    → 8: Nested setImmediate (Check Phase)
    → 7: Nested setTimeout (Timers Phase of the following loop tick)

Event Loop Anti-Patterns and Production Solutions

1. Event Loop Starvation with Recursive nextTick

Because process.nextTick() runs continuously until empty, calling it recursively prevents the event loop from ever entering the Poll or Timers phase:

// DANGEROUS: Starves the event loop entirely
function recursiveStarvation() {
  process.nextTick(recursiveStarvation);
}
recursiveStarvation();
// HTTP server stops accepting connections!

Solution: Use setImmediate() for recursive task chunking. Because setImmediate runs in the Check phase, the event loop still processes pending I/O and timers between iterations.

2. Offloading CPU-Bound Tasks with Worker Threads

The event loop is designed for high-concurrency I/O-bound tasks (databases, network requests, file reading). Heavy computation (cryptography, PDF generation, machine learning, image resizing) blocks the call stack and degrades throughput.

For CPU-intensive tasks, utilize Node’s node:worker_threads module to run computations on real OS threads without blocking the event loop:

const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');

if (isMainThread) {
  function runHeavyCalculation(data) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, { workerData: data });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  }

  // Event loop remains fully responsive to HTTP requests
  runHeavyCalculation({ iterations: 1e9 }).then(result => {
    console.log('Computation finished:', result);
  });
} else {
  // Executes on a separate OS thread
  let sum = 0;
  for (let i = 0; i < workerData.iterations; i++) {
    sum += i;
  }
  parentPort.postMessage({ sum });
}

To deepen your mastery of Node.js backend engineering and asynchronous concurrency, explore our related architectural tutorials:


Frequently Asked Questions

Why is JavaScript single-threaded if libuv uses a thread pool?

JavaScript code execution (the V8 engine) runs strictly on a single thread—the main event loop thread. However, libuv creates and manages a background thread pool (default size: 4 threads, configurable via UV_THREADPOOL_SIZE) used for expensive I/O tasks that operating systems do not support asynchronously (such as file system operations and DNS lookups). Network I/O (TCP/HTTP) uses non-blocking OS notification primitives (epoll on Linux, kqueue on macOS, IOCP on Windows) and does not consume thread pool resources.

What is the difference between setImmediate() and setTimeout(fn, 0)?

setTimeout(fn, 0) schedules a callback in the Timers phase with a minimum elapsed threshold of 1 millisecond. setImmediate() schedules a callback in the Check phase, designed to run immediately after the poll phase handles pending I/O. Inside any I/O callback (such as reading a file or handling an incoming socket), setImmediate() will always execute before setTimeout(fn, 0).

When should I use process.nextTick()?

Use process.nextTick() only when you need to give users the ability to assign event listeners before an event is emitted, or to allow constructors to finish initializing state before invoking a callback asynchronously. Avoid using process.nextTick() for long-running iterative tasks to prevent starving the event loop.

Article maintained by Mohit Kumar, Senior Full Stack & Cloud Architect. Have technical questions or architecture suggestions? Feel free to reach out via our Contact Us page.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top