Sobes.tech
Senior

Explain the event loop: components and how they work together. Explain macro and micro tasks.

sobes.tech AI

Answer from AI

Event loop — is a mechanism in Node.js that allows non-blocking I/O operations and handles asynchronous operations.

Main components of the event loop:

  • Call Stack — the stack of calls where the current code is executed.
  • Event Queue (Task Queue) — the queue of macrotasks, where callbacks are placed after asynchronous operations complete.
  • Microtask Queue — the queue of microtasks, where promises and some other tasks are placed.

How they work together:

  1. Code from the Call Stack is executed.
  2. When the stack is empty, the event loop first processes all microtasks from the Microtask Queue.
  3. Then, one macrotask is taken from the Event Queue and executed.
  4. The cycle repeats.

Difference between macro- and microtasks:

  • Macrotasks — are, for example, event handlers, setTimeout, setInterval, I/O operations.
  • Microtasks — are promises (Promise.then/catch/finally), process.nextTick.

Microtasks have a higher priority and are executed immediately after the current code and before the next macrotask, allowing for more efficient management of asynchronous operations.