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?
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.
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
- 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.
Next part of What is Event Loop in NodeJS is to learn about the nodejs flow.
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.
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.
- 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.
Following graph will show how poll phase will handle the callbacks
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.
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() 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.
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.
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