Skip to content

Event Loop Internals

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.

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"| G
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: 4
// RAF runs BEFORE the next paint, AFTER microtasks
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
requestAnimationFrame(() => console.log('raf'));
// Output: promise, raf, timeout
  • Event loop is provided by the host environment, not JS engine
  • Each iteration: 1 macrotask → all microtasks → render (if needed)
  • requestAnimationFrame runs before paint, after microtasks