🚀 Mastering JavaScript Event Loop — Simplified for Interviews
↔️ In JavaScript, everything starts with the Call Stack- a synchronous structure (Code Executes LIFO order ).
Because JavaScript is single-threaded, it leans on Browser Web APIs (like setTimeout, fetch, DOM APIs) to handle async operations.
🧠 Browser Superpowers (Web APIs)
Browsers provide extra features beyond the JavaScript engine, called Web
APIs, including :
- setTimeout, setInterval
- DOM Manipulation APIs
- fetch (for network requests)
- localStorage
- console
- location
- Bluetooth access, Geolocation, etc.
These features are accessible via the window object in browsers.
When an asynchronous operation (like setTimeout or fetch) is triggered:
- It is registered in the Web API Environment provided by the browser.
- Once completed (like a timer expiring or a network request finishing), the corresponding callback is placed into queues — waiting for the Call Stack to be free.
🔥 Event Loop
The Event Loop continuously monitors:
- If the Call Stack is empty.
- If there are pending callbacks in the Queues.
Its main job:
When the Call Stack is empty, the event loop moves queued callback functions to the Call Stack for execution. Callback functions in the Microtask Queue are given priority and executed first Then Callback (Task) Queue.
🧩 Microtask Queue vs Callback (Task) Queue
There are two important types of queues:
Microtask Queue:
- Higher priority than the Callback Queue.
- Promise .then() / .catch() / .finally() handlers call back functions and MutationObserver callbacks function
Callback Queue (Task Queue) :
- Lower priority.
- Includes:
- setTimeout , setInterval , UI rendering callbacks , DOM event callbacks
Important:
Before picking a task from the Callback Queue, the Event Loop empties all microtasks first.