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:
- Call Stack → What is currently executing
- Callback Queue / Task Queue → Tasks waiting to be executed
- 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
-
-
Stores callbacks from async operations (like
setTimeout)
4. Microtask Queue
setTimeout)
-
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:
-
"Start"→ goes to call stack → prints -
setTimeout→ moved to Web APIs → timer starts -
Promise→ goes to Microtask Queue -
"End"→ executes immediately
Now call stack is empty 👇
-
Event loop checks:
-
Microtask queue first → runs
"Promise"
-
Microtask queue first → runs
-
Then callback queue → runs
"Timeout"
✅ Final Output:
Start
End
PromiseTimeout
⚡ Priority Order
- Call Stack
- Microtask Queue (Promises, nextTick)
-
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.