Understanding Event Loops in Node.js

Node.js is known for being an open-source, cross-platform JavaScript run-time environment, expanding JavaScript’s utilities for providing a server-side experience. However, Node.js also introduces a vast variety of features capable of controlling I/O callbacks at run-time, known as event loops.

An event loop is a design pattern which waits/dispatches task events, granting the application access to non-blocking I/O operations. Event loops in Node.js follow a strict order of operations when code is executed. Below is a visual depiction of what these order of operations look like:

In this depiction you have the incoming connections and data entering into the event table where the data filters out in divisions known as Phases. Each phase has a specific priority in the event table, organized above. Below are the types of Phases that exist in Node.js:

  • Timers: Callbacks scheduled by methods such as setTimeout(), and setInterval().
  • Pending callbacks: Executes I/O callbacks deferred to the next loop iteration.
  • idle/prepare: Works with internally used I/O callbacks.
  • I/O Poll: Retrieves I/O events and runs callbacks which will register at call-time.
  • Closing callbacks: Determines when the callback will be closed.

The best way to demonstrate the functionality of event loops is by narrowing down on one of the previously mentioned phases. For the purpose of this blog, I will be focusing primarily on the Timer phase and methods.

To start, let’s take a look at the useful methods which can display the functionality of event loops in Node.js.

nextTick(): Waits for the tick after code is executed for the callback to execute.

The code above will execute in the order of, Start, End, Tick Callback 1, and Tick Callback 2.

In the example shown above, the start and end logs are called first, then once the code finishes, the tick callbacks are then executed afterwards.

setTimeout(): Determines when the callback will be executed based on the specified duration argument.

setImmediate(): Executes the callback IMMEDIATELY after the function/callback this method is placed in finishes.

The code above will execute in the order of First, Last, Immediate, and timeout.

In the example depicted above, the fs module is used to make a readFile() method that logs the callback data stored. What will log first will be “First” and “Last”, while right afterwards “Immediate” is executed, despite the setTimeout’s timer argument set to 0 due to the callback already finishing.

Hopefully these few methods shown, along with the information given, would provide more insight on how the event loops in Node.js operate, communicate, and create I/O operations for any application!

JS Dev