Topic 24 of 37
The Event Loop Architecture
Overview
JavaScript is single-threaded, meaning it can only do one thing at a time. The Event Loop is the secret mechanism that allows JS to perform non-blocking, asynchronous operations (like network requests). It orchestrates the Call Stack, the Web APIs, the Macrotask Queue (callbacks), and the Microtask Queue (Promises).
Syntax
1) Sync code executes immediately. 2) Microtasks execute immediately after the current stack is empty. 3) Macrotasks execute only after all Microtasks are cleared.
Execution Order
javascript
console.log("1. Sync code (Call Stack)");
setTimeout(() => {
console.log("4. Macrotask (setTimeout)");
}, 0);
Promise.resolve().then(() => {
console.log("3. Microtask (Promise)");
});
console.log("2. Sync code (Call Stack)");Common Pitfalls
- Writing an infinite loop of Promises (Microtasks) will completely freeze the browser UI, because the Macrotask queue (which handles rendering) will never be reached.
Interview Tips
- Always remember: The Microtask Queue has higher priority than the Macrotask Queue. All promises resolve before the next setTimeout runs.
Real-World Example
Using setTimeout(fn, 0) to yield to the browser's rendering engine.
example
javascript
// Heavy calculation blocking the UI
// Use setTimeout to push the rest of the work to the end of the queue, allowing the UI to paint.
function processLargeArray(arr) {
setTimeout(() => {
// Process chunk of array
}, 0);
}