Event Loop Internals
Event Loop Internals
Section titled “Event Loop Internals”Introduction
Section titled “Introduction”The event loop is not part of JavaScript itself — it’s provided by the host environment (browser or Node.js). This deep dive covers what happens at the engine level.
Full Architecture
Section titled “Full Architecture”flowchart TD A["Call Stack (V8)"] B["Heap (V8)"] C["Web APIs (Browser)"] D["Macrotask Queue"] E["Microtask Queue"] F["Event Loop"] G["Render Pipeline"]
A -->|"Async call"| C C -->|"Callback ready"| D C -->|"Promise resolves"| E F -->|"Monitor"| A F -->|"Process all"| E F -->|"Process one"| D F -->|"Render if needed"| GExecution Order (Deep)
Section titled “Execution Order (Deep)”console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => { console.log('3');
setTimeout(() => console.log('4'), 0);
Promise.resolve().then(() => console.log('5'));});
console.log('6');
// Output: 1, 6, 3, 5, 2, 4// Step-by-step:// 1. Sync: 1, 6// 2. Microtask queue: 3, 5 (promises)// 3. Macrotask queue: 2// 4. Next macrotask: 4requestAnimationFrame Timing
Section titled “requestAnimationFrame Timing”// RAF runs BEFORE the next paint, AFTER microtaskssetTimeout(() => console.log('timeout'), 0);Promise.resolve().then(() => console.log('promise'));requestAnimationFrame(() => console.log('raf'));// Output: promise, raf, timeoutSummary
Section titled “Summary”- Event loop is provided by the host environment, not JS engine
- Each iteration: 1 macrotask → all microtasks → render (if needed)
requestAnimationFrameruns before paint, after microtasks