Node.js Event Loop

Subject: Node.js

What Is the Event Loop?

The event loop in Node.js is responsible for managing asynchronous operations. It continuously monitors the callback queue and executes functions when async operations like file reads, network calls, or timers complete.

It enables Node.js to:

  • Run JavaScript code
  • Perform non-blocking I/O
  • Handle thousands of tasks using a single thread

Why Node.js Uses the Event Loop

Traditional web servers use multithreading to manage concurrent clients. Node.js uses a single-threaded event loop, which offers:

  • Lower memory usage
  • Greater scalability
  • High performance for I/O-bound operations

How the Event Loop Works

  1. Node.js executes all top-level code.
  2. Async operations (e.g., setTimeout, fs.readFile) are offloaded to the thread pool.
  3. When these tasks complete, their callbacks go into the callback queue.
  4. The event loop checks the queue and runs the callbacks one by one.
  5. Callbacks are only executed when the call stack is empty.

Event Loop Phases

The event loop has multiple phases that handle different types of tasks:

  • Timers: Executes callbacks from setTimeout() and setInterval()
  • Pending Callbacks: Handles specific system operations
  • Idle/Prepare: Used internally
  • Poll: Retrieves new I/O events and executes I/O callbacks
  • Check: Executes setImmediate() callbacks
  • Close Callbacks: Executes close event handlers (e.g., socket closure)

Event Loop in Action: Example

Output:

Explanation:

  • Start and End run immediately as synchronous code.
  • fs.readFile is async and queues its callback after the file is read.
  • setImmediate() executes in the check phase.
  • setTimeout(..., 0) is scheduled in the timer phase and runs later.

Visual Representation


When Event Loop is Blocked

Blocking occurs when long-running synchronous code prevents the event loop from executing queued callbacks.

Example of Blocking:

This freezes the server, making it unresponsive.


Best Practices

  • Avoid long-running synchronous code
  • Always use asynchronous APIs like fs.readFile, setTimeout
  • Use worker_threads for CPU-heavy tasks
  • Use process.nextTick() and setImmediate() wisely

Key Takeaways

  • The event loop enables Node.js to perform async operations on a single thread
  • It manages callback queues and executes them in a specific order
  • Efficient use of the event loop results in scalable applications
  • Understanding the event loop helps avoid performance bottlenecks
Next : Node Architecture