What is the JavaScript Event Loop in depth?
Answer
The event loop in depth: JavaScript runtime has the call stack (synchronous execution), heap (memory allocation), and Web APIs. When async operations (fetch, setTimeout) are initiated, they are handed to Web APIs which process them outside the stack. On completion, callbacks are queued. The loop checks: if the call stack is empty, process ALL microtasks (Promise callbacks, queueMicrotask, MutationObserver) — drain the entire microtask queue, including any new microtasks added during processing. Then take ONE macrotask (setTimeout, setInterval, I/O, UI events). Then process all microtasks again. Then render (if needed). Repeat. Key insight: a Promise chain can produce many microtasks synchronously — if you chain thousands of .then() calls, rendering and macrotasks are blocked until all microtasks complete. requestAnimationFrame fires before rendering, after macrotasks. queueMicrotask(fn) queues a microtask directly. In Node.js: process.nextTick() runs before Promise callbacks; setImmediate() runs after I/O callbacks. Understanding this ordering is crucial for debugging race conditions and performance issues.
Previous
What is the Abstract Equality Comparison algorithm?
Next
What are JavaScript Proxy traps in depth?