What is Event Loop in NodeJS and How it Works (Explained)

What is Event Loop in NodeJS and How it Works. This articles introduces what node.js is and talks about event loop and the way it operates. 

What is Node.js Server?

NodeJS is an event driven runtime environment that is implemented based on Javascript architecture which is used to develop many scalable front end and backend applications. Node.js Server uses lightweight framework that includes bare minimum modules. It is also asynchronous, performs faster than other frameworks.
it runs on multiple platforms likeWindows, MAC or Linux.

What is the Event Loop?

Node.js is based on a non blocking model and the event loop is the concept used by Node.js to facilitate this non blocking model. Modern kernels can handle multiple operations as they are multi threaded. The kernel notifies Node.js when one task is completed and allows it to add the necessary call back to the event queue.

Javascript is an event driven language. Since Node.js is based on JavaScript, it is single threaded and behaves the same way as JavaScript. This architecture allows Node.js developers to add listeners to events. Callbacks start executing as the events trigger the listeners.

Components of Event Loop

Next part of the tutorial of What is Event Loop in NodeJS is to introduce components of event Loop. It is initialized when Node.js is started and it processes the given input scripts and starts executing the event loop.

The event loop is consistent with the following phases

  • Timers.
  • Pending callbacks.
  • Idle and  prepare phase.
  • Poll phase.
  • Check phase.
  • Closing callbacks.

When the event loop initiates a specific phase, it executes the specific tasks of the phase. These tasks are there in a callbacks queue which is served on a first in and first out (FIFO) basis. The tasks in this queue will be executed until the tasks are completed or the upper limit of the callbacks is exceeded. In the second scenario, those tasks will move into the following phase in the flow.

Furthermore, Node.js checks if there are any waiting asynchronous input, outputs or timer tasks before running the next phase. The loop will be shut down if there is no such activity.

Nodejs flow

Next part of  What is Event Loop in NodeJS is to learn about the nodejs flow. 

Timers

The settled or scheduled callbacks are executed after a determined threshold time than the defined time. The timer takes care of running the callback events at the given time. These timer callbacks will be executed soon after the predetermined time gap. However, other scheduled or already running callback events can affect this time gap. The setInterval() and setTimeout() functions are used to schedule the tasks.

setInterval() method is used to schedule repetitive tasks. When one such task is executed, it is stored back in the queue for the next scheduled repetitive execution. The time mentioned before is not the specific time that the callback is executed. It is the time it will take to be queued for the execution.

On the other hand, setTimeout() method is used to schedule a task to be executed after a given minimum threshold. This time will be measured in milliseconds.

Pending callbacks

This phase consists of the callbacks that are there as a result of the system operation. Errors such as TCP errors occur in the event flow due to connectivity issues while trying to connect. In such cases,  that task will be added to the list of pending callbacks.

Idle and prepare

This phase is there for internal task management. The event loop performs the internal callbacks in this phase. The main purpose of this phase is to gather information and plan the execution flow and the process. This phase is not exposed to the client-side or does not affect the client deliverables or activities.

Poll Phase

The poll is the phase where all the JavaScript experts are executed. This phase is responsible for managing the workload of input and output scripts. The poll has two important tasks. Only one of the following functions will happen when the event loop starts this phase.

  • Determining the blocking and polling durations for the inputs and outputs
  • Processing tasks in the queue.

When poll queues already have some callbacks, they will iterate and execute these callbacks synchronously till all the tasks are finished executing or the maximum call back limit is reached.

The event loop will check for two other scenarios when the poll queue has no callbacks.

If scripts are being scheduled with the setImmediate() method, the event loop will skip the poll phase and move into the check phase to execute those scripts.

If the scripts are not set using the setImmediate() method, the event loop will wait until callbacks are added to the queue to execute them as soon as they are added.

When the poll is empty, the event loop continually checks for the time threshold to reach completion. If there are already any timers, it will jump back to the timer phase to execute them.

Node.js callback

Following graph will show how poll phase will handle the callbacks

Check Phase

Once the poll phase is completed, the check phase will be started to execute the existing callbacks. This phase will be triggered if scripts are scheduled with the setimmediate() method. It happens as soon as the poll phase is idled.

Methods scheduled with setImmediate() will be executed before any other timers.

Closing callbacks

The event loop will enter this phase when a socket is closed abruptly ( especially with the socket. destroy() method). In such a scenario, the close event will be emitted, or else it can be emitted through the process.nextTick() method.

In simple words, the process. exit() method is called in when a task is to be removed from the queue. The event loop will be wrapped up to execute the next cycle when it happens. This is a cleaning phase of the executions.

Process.nextTick()

Process.nextTick() is not a part of the event loop. Once a task is executed successfully, the Process.nextTick() queue will be processed despite the current phase. At any time process.nextTick() is being called, all the callbacks passed into that queue will have to be resolved before moving into the next phase. It can be a reason to starve the input/outputs as it prevents the event loop from entering the poll phase.

That way, we can tell the JS engine to process a function asynchronously (after the current function) as soon as possible and not queue it.

It is used to tell the Javascript engine to process this function asynchronously date the current phase without requesting it. This is a kind of order to be executed as soon as the current phase is ended.

Event Loop Node.js

What is Event Loop in NodeJS? The event loop is the backbone of Node.js applications, which keeps them running. In a running application, the event loop will notice the request of the client and work on responding. So basically, all the client requests and responses are passed through the event loop. Hence this process should not be blocked at any time. If it is blocked, the current and new clarinet will not get any response until the blocked request or task is processed and released.

Therefore it is critical to ensure that all the JavaScript callbacks are executed properly and promptly to make the application function without any freezing activity.

As a best practice, always monitor the event loop metrics such as callback computational score, loop latency, execution time, etc., while coding to make sure that any ongoing task is not blocking your Node.js application.

What is Event Loop in NodeJS and How it Works Conclusion

Node.js consists of single threaded processes. Hence it is vital to manage the tasks well when writing multi threaded scripts. The event loop concept is introduced to avoid complexity in development. It is responsible for offloading input and out tasks to the relevant APIs. Therefore, core Node.js can continuously run the JavaScript code while the C++ APIs are looking into handling asynchronous background operations. By then, Node.js imitated the multi threading concept allowing the developers to write non blocking code.

Avatar for Shanika Wickramasinghe
Shanika Wickramasinghe

Senior Software Engineer at WSO2 which is the 6th largest Open Source Software Company in the World. My main skills are machine learning and software development. I have 5+ years of experience as a Software engineer.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x