Sobes.tech
Middle+

Tell me about the Event Loop.

sobes.tech AI

Answer from AI

Event Loop — is a mechanism that allows Node.js to perform non-blocking operations despite its single-threaded nature. It constantly checks the event queue and invokes the corresponding callbacks when operations complete.

Working principle:

  1. Node.js starts the Event Loop.
  2. Asynchronous operations (e.g., file reading, network requests) are sent to system calls or internal queues.
  3. When an operation completes, the corresponding callback is placed in the event queue.
  4. The Event Loop processes these callbacks sequentially, invoking them in the main thread.

This allows efficient resource utilization and prevents blocking program execution.

Example:

console.log('Start');
setTimeout(() => {
  console.log('Timeout callback');
}, 1000);
console.log('End');

The output will be:

Start
End
Timeout callback

Because setTimeout registers a callback that will execute later, and the Event Loop continues executing the current code.