Event Loop in Node.js
Last updated on Feb Tue, 2023 5603

- What is Node.js?
- What is the Event Loop?
- Nodejs Event Loop Architecture
- Phases of the Event loop
- Monitoring the Event Loop
- Tuning the Event Loop
- Conclusion
What is Node.js?
Leveraging Chrome's JavaScript runtime, Node.js is a platform for quickly building scalable network applications. It provides an occurrence-driven, non-blocking I/O method for data-intensive real-time applications that run across scattered devices, keeping it lightweight and effective. It is open-source and free to use. It also provides an excellent development environment, which makes it the ideal framework for web-based apps. A large developer community for Node.js also constantly creates new libraries as well as modules to aid with development.
Because Node.js applications are written in JavaScript and can run on Mac OS X, Windows, and Linux, they are completely cross-platform. Due to its event-driven architecture & non-blocking I/O strategy, Node.js is compact and efficient. It is perfect for distributed, data-intensive real-time applications because of these features. There are several considerations to make when developing Node.js apps. Since Node.js is asynchronous, you should first use promises, async functions, callbacks, or events to manage data flow. Second, you must be careful not to stall the thread by doing time-consuming operations since Node.js currently solely supports a single thread.
Become a master of Node.JS by going through this HKR Node.JS Training !
What is the Event Loop?
Threads
Before understanding Event Loop, it is important to understand Threads. When we start a programme, we generate an example of it, and we have internal components known as threads attached to that instance. A thread can be thought of as a group of tasks that our CPU must carry out on our behalf. The OS scheduler, a component of our operating system, is in charge of managing the scheduling mechanism, which is utilised to decide which thread to run at any given time.
Event Loop
A thread is created automatically each time a Node programme is executed. The only thread in which the entirety of our codebase will be run is this one. The so-called event loop is created inside of it. This loop's function is to schedule the tasks that our single thread should be working on at any given moment.
Please take note that even when we execute our programme immediately, the event loop doesn't appear right away. In actuality, it doesn't start until the entire application has finished running.
The following are some of the features of the Event Loop:
- An event loop is a never-ending cycle that awaits tasks, completes them, and thereafter sleeps until additional tasks are delivered.
- Only after the call stack is empty, or when there are no running tasks, does the event loop begin to process tasks from the event queue.
- We can use promises and callbacks with the event loop.
- The tasks in the event loop are carried out in reverse chronological order.

Node JS Training
- Master Your Craft
- Lifetime LMS & Faculty Access
- 24/7 online expert support
- Real-world & Project Based Learning
Nodejs Event Loop Architecture
Let us try to understand the Node.js Event Loop working via an example:
Example:
console.log("XYZ");
setTimeout(function(){
console.log("ABC");
}, 1000);
console.log("DEF");
Output:
XYZ
DEF
ABC
In the aforementioned example, the task is eliminated from the call stack once the first console log statement is sent to it, logging "XYZ" on the console and pushing the task to the call stack. The job is then delivered to the operating system, and the setTimeout is added to the queue, and also the timer for the task is set. After that, this job is eliminated from the stack. The task is then popped off the stack when the third console log statement is sent to the call stack and "DEF" is printed to the console.
Whenever the timer defined by the setTimeout function (in this example, 1000 ms) expires, the callback is sent to the event queue. The event loop takes the task at the head of the event queue & feeds it to the call stack whenever the call stack is empty. The instruction is carried out by the callback function of the setTimeout function, which also removes the task from the stack and logs the message "ABC" on the console.
Working
Node.js commences running the event loop after initializing the event loop, parsing the input script that may include async API calls, and scheduling timers. The initial input script for the previous example contained console.log() statements as well as a setTimeout() function to set a timer.
A unique library module named libuv is used by Node.js to carry out async activities. The libuv thread pool is a unique thread pool that is managed by this library and the back logic of Node. Four threads from this pool are utilised to delegate tasks that are too complex for the event loop. Examples of these operations are I/O activities, opening and closing connections, and setTimeouts.
A callback function is invoked whenever the thread pool wraps up a task, and it deals with errors (if any) or performs other actions. The event queue receives a callback function like this one. The event moves through the event queue and delivers the callback to the call stack when the call stack is empty.
Want to know more about Node.Js, visit here Node.Js Tutorial !

Subscribe to our youtube channel to get new updates..!
Phases of the Event Loop
Let us now learn about the different phases of the event loop in more detail.
- Timers: The event loop begins processing any callback functions from expired timers first. If a timer expired later while one of the other phases was getting processed, the callback function for that timer will only be invoked when the event loop returns to the first phase. As a result, each queue's callbacks are handled one at a time until there are none left; only then will the event loop go on to the following stage.
- Pending Callbacks: The event loop runs any system-related callbacks during this phase. For instance, if you are developing a node server but another process is already using the port you wish to use to execute the process, the node will produce an error. ECONNREFUSED, some *nix systems might prefer the callback wait for execution because the system software is handling other duties. As a result, these callbacks are added to the execution queue for pending callbacks.
- Idle, Prepare: This phase is for cleaning up. The Event Loop does any callbacks' internal operations during this phase. Technically, neither the length of this period nor its direct influences are conceivable. There is no mechanism in place to ensure code execution throughout this stage. It is mostly used to gather data and plan what has to be done at the Event Loop's subsequent tick.
- Poll: The event loop keeps an eye out for brand-new async I/O callbacks during this stage. Except for the setTimeout, setInterval, setImmediate, and closing callbacks, almost all callbacks are executed.
In essence, the event loop performs two tasks during this stage:
- It will carry out any callbacks that are already queued up in the poll phase callback queue until all callbacks have been cleared from the poll phase callback queue.
- The event loop will remain in the poll phase for a while if there are currently zero callbacks in the queue. This "some time" is also dependent on the following factors:
- The event loop will not stay in the poll phase for very long should there be any callbacks waiting to be processed in the setImmediate queue; instead, it will go to the Check/setImmediate phase. Once more, until the Check/setImmediate phase callback queue is empty, it will begin performing callbacks.
- Whenever the event loop learns that timers have expired and their callbacks are pending to be executed, that is the second situation in which it will leave the poll phase. The event loop will then proceed to the Check/setImmediate phase, the Closing callbacks phase, and finally, the timers phase to begin its next iteration.
Top 30 frequently asked Node.JS Interview Questions !
- Check: The event loop in this phase starts executing each callback that was placed on the queue during the Check phase one at a time till the queue is clear. Once the poll phase gets idle and when there are no more callbacks that need to be executed, the event loop will enter this phase. Typically, during this stage, setImmediate callbacks are carried out.
- Close Callbacks: The event loop runs the callbacks connected to the closure events during this phase, such as socket.on('close', fn) or process.exit ().
Monitoring the Event Loop
It is clear that the event loop regulates all activities within a Node application. This indicates that if we are able to extract measurements from it, they ought to give us useful details about the overall performance and health of an application.
Any monitoring tool needs to provide its own metrics since there is no API for getting runtime data from the event loop. This is what we came up with:
- Tick Frequency: The rate of ticks per second.
- Tick Duration: The length of a tick.
Tuning the Event Loop
Metrics are useless, of course, until you understand how to utilize them to identify potential problems to solve. Here are some recommendations for what to do when it seems like the event loop is losing steam.
- Utilise all CPUs: A Node.js programme is run by a single thread. This shows that on multicore systems, the load isn't dispersed equally across all cores. By using the cluster module that is included with Node, it is easy to spawn a child process for each CPU. Each kid process has a separate event loop, & the master process divides the workload evenly among all of the children.
- Tune the Thread Pool: Libuv for Node.js will create a four-thread pool. You can alter the pool's default size by modifying the environment variable UV THREADPOOL SIZE. Despite the fact that this helps alleviate load issues in I/O-bound apps, we would not advise conducting too many stress tests since a bigger thread pool can still consume up all available memory or CPU.
- Offload the work to Services: If Node.js devotes too much time to CPU-intensive operations, it may be feasible to offload the task to services or even employ another language that is better suited for the purpose.
Conclusion
In this blog, we learned about what Node.js and event loop is and how the node.js event loop work along with the help of an example. We also discussed the phases of the event loop like timers, pending callbacks, idle, prepare, poll, check and close callbacks. We further learned about monitoring and tuning the event loop. If you want to use Node.js effectively, learn how to boost its performance, or just find a new, compelling reason to take on new technology, you must first understand how the event loop works.
Related Articles:
About Author
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.
Upcoming Node JS Training Online classes
Batch starts on 6th Oct 2023 |
|
||
Batch starts on 10th Oct 2023 |
|
||
Batch starts on 14th Oct 2023 |
|
FAQ's
When the function stack is empty, an event loop is anything that moves items from the queue to the function execution stack.
By using the cluster APIs or the previously described child processes, node.js can have several event loops, but by default only uses one on the main thread.
The Event Loop uses just one thread. It serves as the Node JS Platform Processing Model's main building block. Loop also examines every Client Request put in the Event Queue.
The event loop waits for the Call Stack to be cleared prior to pushing callbacks from the Task Queue to the Call Stack. Once the stack has been emptied, the event loop is started, and checks the Task Queue for any callbacks that might be available.