Async

Node.js Event Loop

Understanding the Event Loop

Node.js event loop manages async tasks with phases like timers.

Understanding the Node.js Event Loop

The Node.js event loop is a fundamental concept for understanding how Node.js handles asynchronous operations. It allows Node.js to perform non-blocking I/O operations, despite the fact that JavaScript is single-threaded. The event loop continuously cycles through various phases, executing callbacks and managing asynchronous tasks.

Phases of the Event Loop

The event loop consists of multiple phases, each responsible for handling different types of asynchronous operations. These phases are:

  • Timers: Executes callbacks scheduled by setTimeout() and setInterval().
  • I/O Callbacks: Handles callbacks deferred to the next loop iteration.
  • Idle, Prepare: Internal use only.
  • Poll: Retrieves new I/O events; executes I/O-related callbacks.
  • Check: Executes callbacks scheduled by setImmediate().
  • Close Callbacks: Executes close callbacks, such as socket.on('close', ...).

Timers and I/O Operations

Timers allow you to schedule callbacks to execute after a specified delay. I/O operations, such as reading files or making HTTP requests, are handled in the poll phase. Here is an example demonstrating the use of timers and an I/O operation:

In the example above, the output will be:

Start
End
File Read
Immediate 1
Timeout 1

This demonstrates how the event loop handles different phases. The timers are executed after I/O operations, showing the non-blocking nature of Node.js.

SetTimeout vs SetImmediate

Both setTimeout and setImmediate are used to schedule callbacks, but they work differently. setTimeout schedules a callback to run after a minimum threshold time has elapsed, while setImmediate places the callback in the check phase, allowing it to execute immediately after the polling phase in the current iteration of the event loop.

Previous
Async/Await