The Event Loop is the mechanism that allows JavaScript (which is single-threaded) to handle asynchronous operations like timers, DOM events, and network requests without blocking the main thread.
🔹 How It Works:
- Call Stack:
- Where JavaScript executes functions synchronously (one at a time).
- Web APIs / Background APIs:
- Handles async tasks like
setTimeout,fetch, and DOM events (provided by the browser).
- Handles async tasks like
- Callback Queue / Task Queue:
- Stores callbacks waiting to be pushed to the call stack.
- Event Loop:
- Continuously checks if the call stack is empty.
- If so, it pushes the first task from the callback queue to the call stack.
✅ Visual Example:
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 0);
console.log("End");
Output:
Start
End
Async Task
Even though
setTimeoutis 0 ms, the function is placed in the callback queue and only runs after the call stack is empty.
📝 In Summary:
- The Event Loop ensures non-blocking, asynchronous execution in JavaScript by coordinating between the call stack, Web APIs, and callback queue.
- It allows JavaScript to remain fast and responsive, even with async operations.