DEV Community

Segolene
Segolene

Posted on • Edited on

My Understanding of Event Loop in Nodejs

Normally, Nodejs is an application which use single thread, but through the concept of events and callbacks It can support the concurrency. Every single API use a one thread and control the timing of operations by the use of pulse sent when the previous operations is completed, which means that two operations can not run simultaneously. To maintain the concurrency API use a sync function calls. Node thread keeps events loop and whenever an operation is completed, it send the equivalent event which trigger the execution of events listener function. the function that listen to events act as observers.

Even thought, callbacks look like events, they are different. the event handling works on the observer pattern but callback functions are called when an asynchronous function returns the result.
Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners.

Nodejs is also called event driven programming due to its heavily use of events which This makes it faster than other technologies. immediately after node starts its server; it just initiate its variables, declare functions, then waits for the events to occur. any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter.

Despite the fact that JavaScript is single-threaded,The event loop is what allows Node js to perform I/O operations without being blocked by offloading operations to the system kernel whenever possible.

When Node js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, then begins processing the event loop.
Generally, when the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase's queue until the queue has been exhausted or the maximum number of callbacks has executed.
Each phase has a FIFO queue of callbacks to execute. While each phase is special in its own way, When the queue has been exhausted or the callback limit is reached, the event loop will move to the next phase, and so on.

Top comments (0)