Sobes.tech
Middle+

How does the Event Loop work in Node.js?

sobes.tech AI

Answer from AI

Event Loop is a mechanism that allows Node.js to perform non-blocking I/O operations despite JavaScript being a single-threaded language. The Event Loop continuously monitors the call stack, callback queue, and various event queues (timers, I/O).

Main phases of the Event Loop:

  1. timers: Executes callbacks scheduled by setTimeout() and setInterval().
  2. pending callbacks: Executes callbacks of system operations (e.g., network errors), deferred to the next iteration of the Event Loop.
  3. idle, prepare: Internal phases of the Event Loop.
  4. poll:
    • Determines how long to block and poll for I/O operations.
    • Processes events in the I/O callback queue when their number reaches a certain limit or time runs out.
  5. check: Executes callbacks scheduled by setImmediate().
  6. close callbacks: Executes close event callbacks, e.g., socket.destroy().

process.nextTick() and microtasks (Promise, queueMicrotask()) are executed between phases of the Event Loop and before moving to the next phase or completing the current one. process.nextTick() has a higher priority than microtasks.

// Examples of task scheduling
console.log('Start');

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

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

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

Promise.resolve().then(() => {
  console.log('Promise');
});

console.log('End');

// Typical execution order (may vary depending on Node.js version and load):
// Start
// End
// nextTick
// Promise
// Timeout 0  (executes in timers phase)
// setImmediate (executes in check phase)

The Event Loop allows Node.js to efficiently handle many parallel requests without creating a separate thread for each, ensuring high performance.