NodeJS : Event-Loop


The event loop is a central concept in Node.js that allows it to handle asynchronous operations efficiently. Here’s a breakdown of how the event loop works in Node.js:

Single-threaded, Non-blocking Model: Node.js operates on a single-threaded, non-blocking event-driven model. This means that it uses a single thread to handle multiple concurrent operations asynchronously, without blocking the execution of other code.

Event Loop Phases: The event loop in Node.js has several phases, each responsible for specific types of tasks:

  • Timers: Handles callbacks scheduled by setTimeout() and setInterval().
  • I/O callbacks: Executes I/O-related callbacks, such as network requests and file system operations.
  • Idle, Prepare: Internal phases for preparation and handling of callbacks.
  • Poll: Retrieves new I/O events and executes corresponding callbacks. If there are no I/O events, it waits for callbacks to be added to the queue.
  • Check: Executes setImmediate() callbacks.
  • Close callbacks: Executes close event callbacks, such as socket.on('close', ...).

Event Queue and Callbacks: Asynchronous operations in Node.js typically involve callbacks. When an asynchronous task completes, its callback is placed in the event queue. The event loop continuously checks this queue for pending callbacks and executes them in the appropriate phase.

Example: Let’s consider an example to demonstrate the event loop in action:

When you run this code, it outputs:

Here's what happens:

  • The code starts executing with the console.log('Start') statement.
  • It then schedules a timeout callback using setTimeout() to execute after 1000 milliseconds but doesn't wait for it to complete.
  • The console.log('End') statement is executed.
  • The event loop detects that the timeout has elapsed and executes the timeout callback, resulting in the output Timeout callback executed.
Start
End
Timeout callback executed

console.log('Start');

setTimeout(() => {
    console.log('Timeout callback executed');
}, 1000);

console.log('End');

Non-blocking Nature:

The event loop's non-blocking nature allows Node.js to handle a large number of concurrent connections efficiently. It can perform I/O operations without waiting, making it suitable for applications that require high concurrency and real-time interactions.

Overall, the event loop is a crucial mechanism in Node.js that enables asynchronous programming, efficient resource utilization, and scalability in handling concurrent operations.