Event Loop in JavaScript
JavaScript uses a single thread. Asynchronous operations are processed using the event loop, which processes tasks once the call stack is empty. Promises and async/await simplify async handling.
🧠Main idea:
JavaScript runs in a single thread, meaning it can only do one thing at a time (one line of code at a time).
But we often want to do asynchronous tasks (like fetching data, setting timers) without blocking the rest of the code. This is where the event loop comes into play.
How it works step-by-step:
Call Stack:
- This is where JavaScript keeps track of what function is currently running.
- Only one function can be on top at a time.
Web APIs / Background APIs:
- When we do async tasks (like setTimeout, fetch, etc.), they are handled outside of the call stack (by the browser environment or Node.js).
Task Queue / Microtask Queue:
- Once an async task (e.g., a fetch or timeout) finishes, it sends a callback to the Task Queue (or Microtask Queue for promises).
Event Loop:
- The event loop checks:
- Is the Call Stack empty?
- If yes, it moves the first task from the queue to the call stack and runs it.
- It keeps repeating this forever.
Visual idea:
Quick Example:
Output:
Why this order?
- Start and End run first (normal synchronous code).
- Then Promise runs (promises use the Microtask Queue, which is prioritized).
- Finally, setTimeout runs (tasks from the Task Queue).
Promises and async/await:
- Promises and async/await allow us to write asynchronous code that looks synchronous.
- Under the hood, they still rely on the event loop and the microtask queue.
Even though fetch is async, await makes it look sequential — but the event loop is still managing the behind-the-scenes waiting.