Open In App
Related Articles

Node.js Event Loop

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Node.js is a single-threaded event-driven platform that is capable of running non-blocking, asynchronous programming. These functionalities of Node.js make it memory efficient. The event loop allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by assigning operations to the operating system whenever and wherever possible. 

Most operating systems are multi-threaded and hence can handle multiple operations executing in the background. When one of these operations is completed, the kernel tells Node.js, and the respective callback assigned to that operation is added to the event queue which will eventually be executed. This will be explained further in detail later in this topic. 

Features of Event Loop:

  • An event loop is an endless loop, which waits for tasks, executes them, and then sleeps until it receives more tasks.
  • The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.
  • The event loop allows us to use callbacks and promises.
  • The event loop executes the tasks starting from the oldest first.

Example: 

javascript

console.log("This is the first statement");
  
setTimeout(function(){
    console.log("This is the second statement");
}, 1000);
  
console.log("This is the third statement");

                    

Output:

This is the first statement
This is the third statement
This is the second statement

Explanation: In the above example, the first console log statement is pushed to the call stack, and “This is the first statement” is logged on the console, and the task is popped from the stack. Next, the setTimeout is pushed to the queue and the task is sent to the Operating system and the timer is set for the task. This task is then popped from the stack. Next, the third console log statement is pushed to the call stack, and “This is the third statement” is logged on the console and the task is popped from the stack. 

When the timer set by the setTimeout function (in this case 1000 ms) runs out, the callback is sent to the event queue. The event loop on finding the call stack empty takes the task at the top of the event queue and sends it to the call stack. The callback function for the setTimeout function runs the instruction and “This is the second statement” is logged on the console and the task is popped from the stack.

Note: In the above case, if the timeout was set to 0ms then also the statements will be displayed in the same order. This is because although the callback will be immediately sent to the event queue, the event loop won’t send it to the call stack unless the call stack is empty i.e. until the provided input script comes to an end.

Working of the Event loop: When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedules timers, then begins processing the event loop. In the previous example, the initial input script consisted of console.log() statements and a setTimeout() function which schedules a timer. 

When using Node.js, a special library module called libuv is used to perform async operations. This library is also used, together with the back logic of Node, to manage a special thread pool called the libuv thread pool. This thread pool is composed of four threads used to delegate operations that are too heavy for the event loop. I/O operations, Opening and closing connections, setTimeouts are examples of such operations. 

When the thread pool completes a task, a callback function is called which handles the error(if any) or does some other operation. This callback function is sent to the event queue. When the call stack is empty, the event goes through the event queue and sends the callback to the call stack. 

The following diagram is a proper representation of the event loop in a Node.js server: 

Phases of the Event loop: The event loop in Node.js consists of several phases, each of which performs a specific task. These phases include:

The following diagram shows a simplified overview of the event loop order of operations: 

1. Timers:  This phase processes timers that have been set using setTimeout() and setInterval().

Here is an example of how the timers phase works:

Javascript

console.log('Start');
 
setTimeout(() => {
    console.log('Timeout callback');
}, 2000);
 
console.log('End');

                    

In this example, the setTimeout() function is called with a callback that will print “Timeout callback” to the console after 2000 milliseconds (2 seconds). This function is added to the message queue in the timers phase, and the event loop will process it after the synchronous code is executed. The output will be:

Start
End
Timeout callback

As you can see, the “Timeout callback” is printed after 2 seconds, after the “Start” and “End” are printed, because the setTimeout() function is non-blocking and its callback is processed by the event loop after the execution of the synchronous code.

2. Pending Callbacks: This phase processes any callbacks that have been added to the message queue by asynchronous functions.

Here is an example of how the pending callbacks phase works:

Javascript

console.log('Start');
 
setImmediate(() => {
    console.log('Immediate callback');
});
 
console.log('End');

                    

In this example, the setImmediate() function is called with a callback that will print “Immediate callback” to the console. This function is added to the message queue in the pending callbacks phase, and the event loop will process it after the timers phase. The output will be:

Start
End
Immediate callback

3. Idle, Prepare: The “idle.ignore” phase is not a standard phase of the event loop in Node.js. It means it’s Used internally only. The “idle” phase is a period of time during which the event loop has nothing to do and can be used to perform background tasks, such as running garbage collection or checking for low-priority events.

“idle.ignore” is not an official phase of the event loop, it is a way to ignore the idle phase, meaning that it will not use the time of the idle phase to perform background tasks.

An example of using idle.ignore can be:

Javascript

const { idle } = require('idle-gc');
 
idle.ignore();

                    

Here we are using the idle-gc package, which allows you to ignore the idle phase. This can be useful in situations where you want to ensure that the event loop is always busy and that background tasks are not performed.

It’s worth mentioning that, in general, the use of idle.ignore is not recommended, as it could cause performance issues, we should only use this if we have a very specific use case that requires it.

4. Poll: This phase is used to check for new I/O events and process any that have been detected.

Here is an example of how the poll phase works using a readStream:

Javascript

const fs = require('fs');
const readStream = fs.createReadStream('./file.txt');
 
console.log('Start');
 
readStream.on('data', (chunk) => {
    console.log(chunk.toString());
});
 
console.log('End');

                    

In this example, a readStream is created to read the contents of a file. The ‘data’ event is added to the message queue in the poll phase, and the event loop will process it after the pending callbacks phase. The output will be the content of the file.

5. Check This phase processes any setImmediate() callbacks that have been added to the message queue.

Here is an example of how the check phase works:

Javascript

console.log('Start');
 
setImmediate(() => {
    console.log('Immediate callback');
});
 
console.log('End');

                    

In this example, the setImmediate() function is called with a callback that will print “Immediate callback” to the console. This function is added to the message queue in the check phase, and the event loop will process it after the poll phase. The output will be:

Start
End
Immediate callback

6. Close Callbacks: This phase processes any callbacks that have been added to the message queue by the close event of a socket. This means that any code that needs to be executed when a socket is closed is placed in the message queue and processed during this phase.

Here is an example of how the close callbacks phase works:

Javascript

const net = require('net');
const server = net.createServer((socket) => {
    socket.on('close', () => {
        console.log('Socket closed');
    });
});
 
server.listen(8000);

                    

In this example, a server is created using the net module, and the ‘close’ event is added to the message queue in the close callbacks phase with a callback that will print “Socket closed” to the console. This event will be triggered when the server’s socket is closed by the client and the callback will be processed by the event loop during the close callbacks phase.

It’s important to note that the order of execution of these phases can vary depending on the specific implementation of the event loop, but generally, the event loop will process them in the order mentioned above.

Each phase is executed in order, and the event loop will continue to cycle through these phases until the message queue is empty.

Conclusion: The event loop is a powerful feature of Node.js that enables it to handle a high number of concurrent connections and perform non-blocking I/O operations. Understanding how the event loop works is essential for building efficient and performant server-side applications in Node.js. With a better understanding of the event loop, developers can take full advantage of the capabilities of Node.js and build high-performance, scalable applications.



Last Updated : 15 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads