NodeJS Development

How Does The Event Loop Work In Node.Js?

20th Apr 2023

An essential idea in Node.js is the event loop. It makes it possible to know Node's asynchronous operations and non-blocking I/O. It describes the processes that turn Node into a productive, powerful, and well-liked contemporary framework. This guide is helpful for Node.js developers from our  Node.js development company in India who want a better grasp of what's going on within every application and who want complete control over every phase of an application's life cycle.

What Is The Event Loop?

The event loop enables Node.js to execute non-blocking I/O operations by offloading tasks wherever feasible to the system kernel. The majority of recent kernels support multiple threads (they can handle multiple operations at the same time). Node.js receives an update (from the kernel) when one of these kernel actions is finished, and a callback is then added to the poll queue to be ultimately performed.

Node.js starts by setting up the event loop, processing the code supplied (index.js or any other application entry point), which may perform asynchronous calls, schedule timers (setTimeout,...), and call process.nextTick(), etc., before beginning to process the event loop.

A FIFO (first-in, first-out) queue of callbacks must be executed for each phase. The event loop typically conducts any activities unique to each phase when it enters that phase, then executes callbacks in that phase's queue until that phase is complete (the queue has been exhausted, or the maximum number of callbacks has been executed). The event loop will then advance to the following phase and resume running callbacks, among other things.

Event Loop Phases

As long as the application's code needs to be run, the Event Loop's various stages will be repeated. Depending on the OS, there are seven or eight overall stages; however, Node.js only utilizes six.

  • Timers
  • Pending callbacks
  • Prepare, idle
  • Poll
  • Check
  • Close callbacks

Node.js checks for any asynchronous I/O or timers between each event loop iteration and properly terminates itself if none are present.

Phase 1: Timers

Timer functions in Node.js perform callbacks after a predetermined amount of time. Two global methods are provided by the core timers module at our Node.js development company in India: setTimeout() and setInterval ().

Instead of specifying the precise moment that a callback should be invoked, a timer defines the threshold after which it may do so. Once the predetermined time has passed, timer callbacks will start running as soon as they can be scheduled. The OS scheduling or the execution of other callbacks may cause a delay.

Let's examine the Node.js documentation example. A timeout with a 100-millisecond threshold is what we want to plan once a script begins reading a file asynchronously (which takes 95 milliseconds):

Because fs.readFile() has not been completed when the event loop reaches the poll phase, it has an empty queue; thus, it will wait for the amount of ms remaining until the soonest timer's threshold is met. While waiting for 95 milliseconds, fs.readFile() completes reading the file, and its callback, which takes 10 milliseconds to complete, is added to the poll queue and performed. There are no more callbacks in the queue after the callback completes, so the event loop recognizes that the soonest timer's threshold has been reached and moves back to the timer's phase to execute the timer's callback. In this case, the time between the scheduled timer and its callback being executed is 105ms.

Running timer callbacks as part of the Event Loop illustrates the non-obvious behavior that a timer's wait time is not accurate but rather a minimum amount of time that must pass before the callback is queued for execution.

Phase 2: Pending Callbacks

While an application waits for a file to be read, it does not have to wait until the system returns with its contents. It can do something else; drinking a cup of coffee is not an option, so it will resume code execution and asynchronously receive the file's content when ready.

The asynchronous I/O request is registered in the queue, and the main call stack can resume normal operations. The second phase of the Event Loop processes I/O callbacks from successful or failed I/O operations.

Let's see an example:

I/O operations of Node.js for mobile app development include the fs.readFile operation. Node.js will send the request to read a file to your OS's filesystem. The code execution will then instantly go on to myAwesomeFunction after the fs.readFile() instruction (). A callback will be added to the pending queue in the pending callbacks phase after the I/O operation is finished (successful or unsuccessful).

The C library libuv, which implements the Node.js event loop and the platform's asynchronous features, also includes a hard limit (system dependent) before it stops querying for new events, which prevents the poll phase from starving the event loop.

Phase 3: Idle / Waiting

The sole external utility of this phase is for housekeeping. The Event Loop carries out the internal activities of any callbacks. This phase cannot be directly influenced, nor is its duration certain, and code execution is not certain throughout this phase.

Phase 4: Poll

During this stage, all the JavaScript code is run from the file's top to its bottom. Depending on the code, it could do anything right away or queue it up to execute at the event loop's last tick.

The polling phase serves two primary purposes:

1. Estimating the duration of the block and poll for I/O.

2. Controlling instances in the poll queue.

If no timers are set when the event loop reaches the poll phase:

  • The event loop will cycle over its list of callbacks until they have been executed synchronously if the poll queue is not empty (queue has been exhausted, or system-dependent hard limit is reached).
  • One of two additional events will occur if the poll queue is empty:

1. The event loop will conclude the poll phase and go on to the check phase to run any scheduled scripts if setImmediate() was used to schedule them.

2. The event loop will wait for callbacks to be added to the queue before executing them if scripts have not been scheduled by setImmediate().

Depending on the status of the  Node.js for mobile app development, this phase might not occur on every event loop tick.

Phase 5: Check

Callbacks from the special timer setImmediate() in Node.js are carried out within this period. Callbacks can be executed after the poll phase has ended using the setImmediate() function. It uses the libuv API to plan callbacks for execution following the poll phase. Hence, the check phase begins as soon as the poll phase is idle.

The event loop can move directly to the check phase without waiting if the poll phase becomes idle and scripts have been queued using setImmediate().

No matter how many timers are available, script set with setImmediate() will always be run before others.

Phase 6: Close Callbacks

All closure event callbacks are carried out during this phase. For instance, process.exit() is called when a web socket callback closes. At this point, the Event Loop has completed one cycle and is prepared to begin the next. It is typically employed to purge the application's state.

Don't Block The Event Loop

Node.js has a strong feature known as the event loop that allows it to manage several connections simultaneously and carry out non-blocking I/O operations. Building effective and fast server-side applications in Node.js requires understanding how the event loop functions. With a deeper understanding of the event loop, developers at our Node.js development company in India can make the most of Node.js' features and create scalable, high-performance apps.

Read more articles


Protecting Your Cloud Infrastructure using AWS Security Best Practices

To protect your data and ensure the availability and integrity of your AWS resou...


Supabase As A Backend For Flutter Apps Step-By-Step Guide

Supabase, an open-source substitute for Firebase, provides several services l...


The Evolution Of Progressive Web Apps In 2024!

Progressive web applications have become a crucial link between traditional expe...