The event loop in JavaScript is a mechanism that allows non-blocking asynchronous code to run efficiently on a single-threaded engine by managing how tasks are executed in the call stack and callback queues.
⚙️ How It Works (Step-by-Step):
- Call Stack:
JavaScript executes code line by line — each function call is pushed to the stack, and removed when done. - Web APIs / Async Tasks:
Functions likesetTimeout,fetch, or event listeners are handled by browser APIs or Node.js APIs (outside the stack). - Callback / Task Queue:
When async tasks finish, their callbacks are placed into a queue (waiting to be executed). -
Event Loop:
The event loop constantly checks:If the call stack is empty → move the first callback from the queue to the stack.
This process repeats continuously.
🧩 Example:
console.log("1");
setTimeout(() => {
console.log("2");
}, 0);
console.log("3");
Output:
1
3
2
✅ Even though setTimeout is set to 0ms, its callback waits in the task queue until the stack is empty — then the event loop pushes it for execution.
🧠 Event Loop Diagram:
┌────────────────────┐
│ Call Stack │
└────────┬───────────┘
│
┌────────▼─────────┐
│ Web APIs │
└────────┬─────────┘
│
┌────────▼─────────┐
│ Callback Queue │
└────────┬─────────┘
│
Event Loop checks →
🔄 In Short:
The event loop ensures JavaScript can handle asynchronous operations (like API calls or timers) efficiently, without blocking other code from running.