What is the event loop and how does it handle async operations

The event loop is the core mechanism that allows JavaScript (especially in environments like Node.js) to handle asynchronous (non-blocking) operations efficiently—even though JavaScript itself runs on a single thread.


🔁 What is the Event Loop?

Think of the event loop as a manager that continuously checks:

  1. Call Stack → What is currently executing
  2. Callback Queue / Task Queue → Tasks waiting to be executed
  3. Microtask Queue → High-priority async tasks (Promises, etc.)

👉 Its job:

“If the call stack is empty, take the next task from the queue and push it to the stack.”


⚙️ Key Components
1. Call Stack

  • Executes synchronous code line by line

  • Only one function runs at a time
2. Web APIs / Node APIs

  • Handle async operations like:
    • setTimeout
    • HTTP requests

    • File system operations
    3. Callback Queue (Task Queue)

  • Stores callbacks from async operations (like setTimeout)
4. Microtask Queue

  • Stores:
    • Promise.then()
    • process.nextTick() (in Node.js)
  • Higher priority than callback queue


🔄 How Async Code Works (Step-by-Step)

Example:

console.log("Start");

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

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

console.log("End");


Execution Flow:

  1. "Start" → goes to call stack → prints
  2. setTimeout → moved to Web APIs → timer starts
  3. Promise → goes to Microtask Queue
  4. "End" → executes immediately

Now call stack is empty 👇

  1. Event loop checks:
    • Microtask queue first → runs "Promise"
  2. Then callback queue → runs "Timeout"


✅ Final Output:

Start
End
Promise

Timeout
⚡ Priority Order

  1. Call Stack
  2. Microtask Queue (Promises, nextTick)

  1. Callback Queue (setTimeout, setInterval)

🧠 Why Event Loop is Powerful

  • Enables non-blocking I/O
  • Handles thousands of requests efficiently
  • Perfect for:
    • APIs
    • Real-time apps (chat, streaming)
    • Scalable backend systems


🚀 Real-World Analogy

Imagine:

  • Call Stack = Chef cooking
  • Web APIs = Assistants doing prep work
  • Event Loop = Manager assigning tasks
  • Queue = Orders waiting

Chef only cooks when free → manager brings next task.


💡 In Short

The event loop ensures JavaScript can handle async operations by delegating tasks and executing callbacks only when the main thread is free, prioritizing microtasks over normal tasks.

To Top