The Event Loop in Node.js

Node.js·2 min read·Jan 1, 2025

In Node.js, the event loop is the mechanism that allows JavaScript to asynchronously run certain operations in the background without awaiting for their completion, thus allowing the program to run in a non-blocking manner.

When a potentially slow operation is initiated, such as an input/output or a network operation, Node.js automatically delegates it to the system and continues executing other code while it is being processed.

Once the operation is complete, Node.js then notifies the program through callbacks and events that allow it to handle the result or failure of the operation.

Here is a step-by-step overview of the event loop in Node.js:

Step 1: Execute synchronous code

Node.js starts by sequentially executing the synchronous parts of the code, which includes variable declarations, function definitions, and any operations that don't require asynchronous behavior.

Step 2: Offload asynchronous tasks

When the program encounters asynchronous functions like setTimeout(), these tasks are offloaded to the system to be processed in the background, thus avoiding blocking the main execution thread.

Step 3: Enter the event loop

Once all the synchronous code is executed, Node.js enters the event loop and starts processing all the tasks stored in the queues of each phase.

Once all the tasks in the current phase are processed, the loop moves to the next phase, and cycles back to the first phase when it reaches the end.

Phase 1: Timers

This phase processes any callbacks scheduled by setTimeout() or setInterval() if their respective timers have expired.

Phase 2: Callbacks

This phase processes any I/O callbacks that were deferred by the operating system.

Phase 3: Idle

This phase prepares the system for upcoming I/O operations and is used internally by Node.js.

Phase 4: Poll

This phase checks for any new I/O events and processes them by calling their callbacks.

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.