Node.js Event Loop Phases

Node.js – Phases of Event Loop

Once we have understood the Node.js event loop concept and the basic introduction to its phases, let's discuss the functions of the Check handler phase of the event loop. These functions allow the users to control or handle the sequence of the code's execution in the event loop. These functions includes process.nextTick() and set.Immediate() respectively. Both of these functions allow the users to schedule the callback handlers in the loop of events. However, they are processed at separate phases of the event loop.

Understanding process.nextTick()

The process module is one of the global modules provided by the core API of Node.js. We can import the process module by the require() function:

const process = require(‘process’);

However, there is another way to use the process module directly without using the require() function:

process.env

Using the above snippet of code, we can easily access all the environment variables and values of Node.js' system. Similarly, the process.env function provides access to all the process module methods in Node.js without importing with the required () function. Moreover, process.nextTick() is one of the methods of process module. This method allows the developers to accept a function's execution until the subsequent Iteration of the event loop.

The process.nextTick(callback [, ...args]) method have taken a callback and an optional args parameters and queued in the "next tick queue". The point to be noted that every time the event loop takes a complete trip, we would call it a tick.

When we pass a function to process.nextTick(), we are sending instructions to the engine that the following function should be invoked at the end of the current Iteration before the subsequent event loop tick begins:

process.nextTick(() => console.log(“This log is queue using the process.nextTick() method”));

The event loop is busy executing the present function code. After ending of this operation, the JavaScript V8 engine will execute all the functions passed to nextTick calls throughout that operation. This is the method to inform the V8 engine to execute a function asynchronously, as soon as possible without queuing it.

Calling the setTimeout(() => {}, 0) method would process the function after the next tick, much later that while using the nextTick() method, which not only prioritizes the call but also executes it just a moment before the starting of the next tick. Let's see an example demonstrating the working of the process.nextTick() method.

console.log("The First Output");
  // This function will execute in next iteration
process.nextTick(() => {
  console.log("This log is processed in next iteration");
});
console.log("This log is processed in first iteration");

The output of the above code snippet is given as follows:

The First Output
This log is processed in first iteration
This log is processed in next iteration

Understanding setImmediate()

The setImmediate() method is, in fact, an extraordinary timer that works in a distinct phase of the event loop. This method uses a libuv API that allows the users to schedule callbacks for the execution once the poll phase is completed.

The setImmediate(callback [, ...args]) method takes a callback and an optional args parameters like the process.nextTick() function, but instead of queueing the callbacks in the ‘next tick queue’; adds it to the event queue (explicitly the immediate queue). Any function passed as the argument for the setImmediate() method is a callback that is processed in the subsequent iteration of the event loop.

setImmediate(() => console.log('This log is queued using the setImmediate() method'));

Moreover, the execution of callbacks will be executed in the Check handlers phase of the event loop scheduled with the help of the setImmediate() method.

Let’s see an example demonstrating the working of the set.Immediate() method.

console.log("The First Output");
  // This function will execute in next iteration
setImmediate(() => {
  console.log("This log is processed in next iteration");
});
console.log("This log is processed in first iteration");

The output of the above code snippet should look as follows:

The First Output
This log is processed in first iteration
This log is processed in next iteration

The event loop starts executing only when the call stack is zero, queued callbacks are executed in the event queue after the script has finished processing. So, what makes the setImmediate() method different from the setTimeout(() => {}, 0) and from the process.nextTick() methods?

A function passed to process.nextTick() will be executed on the present iteration of the event loop once the present operation ends, which indicates that it will always execute before the setImmediate() and setTimeout(), respectively.

On the other hand, a setTimeout() callback with a delay of 0ms is very similar to the setImmediate() method. The order of execution will depend on several factors; however, they will be executed in the subsequent iteration of the event loop.