×

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.


Related Topics

Node.js Events Module

Introduction to the Node.js events Module As we’ve already discussed, Node.js is a JavaScript runtime with an event-driven architecture designed to perform Asynchronous tasks. In order to accomplish the event-driven architecture,...

4 minutes read.

Node.js Path Module

Understanding the path Module in Node.js The path module is a built-in module of Node.js that provides various methods to interact with the files and directory path names on the device’s...

6 minutes read.

Node.js OS Module

Introduction to Node.js OS Module The OS Module in Node.js provides the Operating System-related Utilities. This module delivers the functions to interact with the Operating System. It also delivers the Operating...

5 minutes read.

Node.js NPM

Node.js – Node Package Manager NPM is an abbreviation for Node Package Manager. It is the default package manager developed by Isaac Z. Schlueter using JavaScript Programming Language, designed for JavaScript Runtime...

7 minutes read.

Node.js Modules

Node.js Modules: At the point when we'll begin composing Node.js applications, we would place all our code into one big node.js file, regardless of how enormous or complex our application...

4 minutes read.

Node.js Callback Concept

Understanding the Concept of Callback A Callback is an asynchronous equivalent for a function that is called at the completion of a task. The Callback helps to avoid any I/O blocking and allows other code to execute...

2 minutes read.

Node.js Discovering Timers

Node.js Discovering Timers: Timers are multi-lingual, and much functional in countless use cases. The Timers are mostly used in many popular programming languages, including Node.js. However, it's pretty simple to...

4 minutes read.

Node.js Error Handling

Node.js – Error Handling: Errors are part of every programming language, and Node.js Environment is not an exception. There are many predefined errors in Node.js, including errors like SyntaxError, RangeError, and...

4 minutes read.

Node.js Event Loop

An Introduction to Event Loop As we have already discussed, Node.js is an Asynchronous platform with a non-blocking I/O. Node.js has awesome features that made it this thriving, and the Event...

5 minutes read.

Node.js Tutorial

Introduction to Node.js: Node.js is a non-proprietary and platform-independent runtime environment for implementing JavaScript code outside of a browser. However, NodeJS isn't a framework and not a programming language. We...

4 minutes read.

Node.js Streams

An Introduction to the Streams Streams are one of the elemental concepts that are introduced to power the applications based on Node.js. These are the method used to handle the data...

6 minutes read.

Node.js File System

Introduction to File System in Node.js FS, abbreviated as File System, is a Node.js Build-in Module, which provides an Application Programming Interface (API) to interact with the File System, and to...

15 minutes read.

Node.js REPL

Node.js REPL: REPL represents the Read Eval Print Loop. REPL is modest; much more, an interactive software development environment similar to the command line shells used in various Operating Systems....

4 minutes read.

Node.js Core Debugger

Node.js – Core Debugger: It’s always a challenge when it comes to debug an application. The Asynchronous workflows of Node.js include an additional layer of intricacy to this difficult process....

3 minutes read.

Node.js Console

Node.js Console: Like the JavaScript console mechanism, a console module is designed for Node.js that provides a debugging console for writing or printing messages. Usually, in JavaScript, a console mechanism is...

4 minutes read.

Difference Between Nodejs Angular and React

A Right JavaScript Framework Within a business, it is necessary to pick the right technology. As much as this applies to the web application and software development, it also applies in...

5 minutes read.

Differentiation of Web Scraping and Web Crawling

Most of us get confused between the word’s web scraping and web crawling, and even some people think they are synonyms for each other. But there is a considerable difference between...

3 minutes read.

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...

4 minutes read.

Difference Between Node.js and Django

Node.js vs Django In Web Application Development, we must have a robust technology to provide strength to our Web application. Node.js and Django both are pretty commanding technologies that help us...

6 minutes read.

Node.js HTTP Module

An Introduction to HTTP Module The http module is a core module in Node.js that uses the Hypertext Transfer Protocol (HTTP) to transfer data. With the help of the http module,...

7 minutes read.