Sobes.tech
Middle+

What is the structure of the event loop in Node.js?

sobes.tech AI

Answer from AI

The event loop in Node.js consists of several phases:

  1. Timers: Executes callbacks from setTimeout() and setInterval().
  2. Pending Callbacks: Executes callbacks from certain system operations, such as TCP socket errors.
  3. Poll:
    • Checks for new I/O events (files, sockets, etc.).
    • Executes callbacks for these events (except those deferred to setImmediate()).
    • If there are timers with zero delay (setImmediate()), it transitions to the check phase.
    • If there are no I/O events to process and the script is not waiting for other operations, it may wait for new events.
  4. Check: Executes callbacks from setImmediate().
  5. Close Callbacks: Executes callbacks for close events, such as socket closures.

Non-standard moments:

  • process.nextTick(): Executes between event loop phases and before any callback in the current phase. Has higher priority.
  • Promises: Promise handlers (.then(), .catch(), .finally()) also execute as microtasks, immediately after the current operational task or function, before the event loop moves to the next phase or processes other macrotasks (like timers or I/O).

Structure of phases:

┌───────────────┐
┌─>│     timers    │
│  └───────────────┘
│  ┌───────────────┐
│  │ pending callbacks │
│  └───────────────┘
│  ┌───────────────┐
│  │ idle, prepare │
│  └───────────────┘      ┌───────────────┐
│  ┌───────────────┐      │   poll     │
└──┤    poll       ├───>│     (I/O callbacks, check timers)  │
  └───────────────┘      └───────────────┘
  ┌───────────────┐
  │   check       │
  └───────────────┘
  ┌───────────────┐
  │  close callbacks  │
  └───────────────┘

Example of setImmediate vs setTimeout execution:

// setImmediate executes in the check phase,
// setTimeout in the timers phase.
// The order of execution depends on external I/O factors,
// but setImmediate is guaranteed to run after the current poll phase.

setTimeout(() => {
  console.log('setTimeout 0ms');
}, 0);

setImmediate(() => {
  console.log('setImmediate');
});

Example of process.nextTick execution:

// process.nextTick() executes before setImmediate and setTimeout,
// even if they have zero delay.

process.nextTick(() => {
  console.log('process.nextTick');
});

setTimeout(() => {
  console.log('setTimeout 0ms');
}, 0);

setImmediate(() => {
  console.log('setImmediate');
});
What is the structure of the event loop in Node.js… - sobes.tech