The event loop is a core concept in asynchronous programming, particularly in Node.js and browsers. It enables non-blocking I/O operations by handling tasks in a single-threaded environment efficiently. 🌀

How the Event Loop Works

  1. Callback Queue
    Tasks like I/O operations are placed in a queue. When the call stack is empty, the event loop processes these queued tasks.

    event_loop_illustration

  2. Microtask Queue
    Promises, async/await, and process.nextTick are handled here. These tasks execute immediately after the current task completes.

    event_loop_phases

  3. Polling Phase
    The event loop checks for new incoming events (e.g., timers, I/O callbacks) and processes them.

    event_loop_polling

Key Concepts

  • Non-blocking I/O
    The event loop allows the program to handle multiple requests without freezing.
  • Async functions
    Use async/await to manage asynchronous operations cleanly.
  • Event Loop Phases
    Read more about the phases to understand its inner workings.

Code Example

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

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

// Output:
// Promise
// Timeout

For deeper insights, check our Async Programming Guide. 🚀