How does the NodeJS Event Loop Work?



The NodeJs Event loop works via libuv..a C library that implements a while loop that runs through the following phases on every "tick" or run of the loop:

1) timers:

  1. setTimeout()

2) prepare

3) poll

4) check

  1. setImmediate()

5) close

For every run of the event loop, the loop passes through these phases. It first checks timers and executes anything that has met the threshold. It then checks prepare internally and moves to the main poll phase. In the poll phase, the loop listens for incoming tcp connections and data availability (read / writes) executes callbacks from these i/o operationsT

Each run of the event loop means all these phases are checked. setImmediate() will always run before setTimeout() because once poll queue is empty it will first check that phase before wrapping back to timers.


the nodeJs event loop polls for incoming tcp connections / data availability via a lower level C library called libuv. This event loop handles network i/o, listening for requests to complete and adding their callbacks to a callback queue.

this callback queue feeds the main execution thread or call stack of your application.


The event loop works in phases:

1) timers:


the event loop is always taking things from a callback queue and running them in the main thread of the event loop. the event loop orchestrates the main call stack and the callback queue..the underlying C++ api libraries and libuv feed the callback least for Node (browser uses webapi)


the event loop is just a while loop...simple as that

this while loop is able to check against non-blocking i/o and listen for activity on different uses additional threads to achieve non-blocking i/o with file system and schedules the registered callbacks to be executed. the event loop orchestrates the sequence in which things fire.