What is the Event Loop?

1. Definition

The Event Loop is a core mechanism in Node.js that allows it to handle multiple operations efficiently using a single thread. It continuously checks the call stack and callback queue and executes tasks without blocking the execution.

2. Key Idea

  • Runs on a single thread
  • Handles asynchronous operations
  • Continuously checks task queues
  • Executes callbacks when ready

3. How it Works

  • Code is executed line by line in Call Stack
  • Async tasks are sent to background (libuv)
  • Completed tasks go to Callback Queue
  • Event Loop pushes callbacks to Call Stack

4. Example

console.log("Start");

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

console.log("End");

👉 Output:

Start
End
Timeout Callback

👉 Even with 0ms delay, callback runs later because Event Loop processes it after the main code.

5. Event Loop Phases (Simplified)

  • Timers (setTimeout, setInterval)
  • I/O Callbacks
  • Idle/Prepare
  • Poll (fetch new I/O events)
  • Check (setImmediate)
  • Close Callbacks

6. Why This is Important

  • Handles multiple requests efficiently
  • Prevents blocking of application
  • Core of Node.js performance
  • Enables asynchronous programming

7. Advantages

  • Efficient concurrency
  • Better performance
  • Handles large number of requests

8. Disadvantages

  • Complex to understand
  • Blocking code affects entire system

Interview Points

  • Event Loop enables non-blocking behavior
  • Works with call stack and callback queue
  • Core part of Node.js architecture
  • Handles concurrency in single thread