Explain How the JavaScript Event Loop Works in Detail
Question Details
Can you explain what happens under the hood when JavaScript executes code asynchronously? Specifically, how does the event loop handle tasks, and why doesn’t setTimeout(0) run immediately?
Suggested Solution
The event loop is the mechanism that allows JavaScript, which is single-threaded, to perform non-blocking operations. It continuously checks the call stack and the task queues (microtasks and macrotasks) and moves tasks to the stack when it's empty.
Key points:
- Call stack: Where functions are executed in order.
- Macrotask queue: Includes setTimeout, setInterval, I/O callbacks.
- Microtask queue: Includes Promises, MutationObserver callbacks. Microtasks run before the next macrotask.
setTimeout with 0 delay does not execute immediately because it is a macrotask.
It waits for the current call stack to empty and all pending microtasks to finish first.
Hence, even setTimeout(0) is asynchronous.
In short, the event loop ensures non-blocking execution by interleaving synchronous code, microtasks, and macrotasks in a predictable order.