22. The Event Loop
Event Loop & Concurrency
This is the most common senior-level interview topic. JavaScript is single-threaded. How does it handle a 5-second API request without freezing the browser? Welcome to the V8 Event Loop.
โ๏ธ The Call Stack
The Call Stack tracks what function is currently running. It operates on a LIFO (Last In, First Out) principle. If a function calls another function, the new function goes on top of the stack.
๐ Web APIs & The Background
When you call setTimeout() or fetch(), the Call Stack hands that job off to the Browser's Web APIs. The Web API handles the timer or network request in the background, freeing up the Call Stack to continue running your other code instantly.
๐ฆ Macrotasks vs Microtasks
When a background task finishes, it doesn't jump straight back into the Call Stack. It gets put in a waiting line.
- Microtask Queue: Extremely high priority. Contains resolved Promises (
.then()/await). - Macrotask Queue: Normal priority. Contains
setTimeoutand DOM events.
The Event Loop is a constantly spinning wheel. It checks the Call Stack. If it's empty, it checks the Microtask Queue first. If that's empty, it checks the Macrotask Queue.
Knowledge Check
Ready to test your understanding of 22. The Event Loop?