> For the complete documentation index, see [llms.txt](https://kdongs.gitbook.io/kdocs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kdongs.gitbook.io/kdocs/nodejs/event-loop.md).

# Event Loop

## [Event Loop](https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick)

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.

{% hint style="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.
  {% endhint %}

{% hint style="warning" %}
ode.js event loop is **slightly different from browsers.**
{% endhint %}

### 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

<img src="https://3232477288-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6jrRvQKMWddG1EeM4Yws%2Fuploads%2FCpiV3Dsy04H1dEJZhReI%2Ffile.excalidraw.svg?alt=media&amp;token=ea844616-8674-4c67-8d49-cca626ddc8d1" alt="" class="gitbook-drawing">
