Event Loop

The event loop is the mechanism that lets Node.js (and browsers) handle:

  • Non-blocking I/O

  • Asynchronous callbacks

  • Concurrency on a single thread

Without it, async programming in JS wouldn’t work.

circle-info

JS is single-threaded, so:

  • If we block the thread (e.g., heavy computation), nothing else can run.

  • To handle multiple concurrent operations, we delegate tasks (like I/O) to the OS/libuv and let the event loop schedule their callbacks when ready.

circle-exclamation

How it works

When Node.js starts, it initializes the event loop, that have multiple phases of execution.

Each phase has a FIFO queue of callbacks to execute.

While each phase is special in its own way, 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.

When the queue has been exhausted or the callback limit is reached, the event loop will move to the next phase, and so on.

Since any of these operations may schedule more operations and new events processed in the poll phase are queued by the kernel, poll events can be queued while polling events are being processed.

As a result, long running callbacks can allow the poll phase to run much longer than a timer's threshold.

Phases of the event loop

Drawing

Last updated