How It Works
How It Works
Section titled “How It Works”Introduction
Section titled “Introduction”The event loop continuously checks the call stack and task queues, moving callbacks to the stack when it’s empty.
Visual Explanation
Section titled “Visual Explanation”flowchart LR A["Call Stack"] B["Web APIs"] C["Macrotask Queue"] D["Microtask Queue"] E["Event Loop 🔄"]
A -->|"Async operation"| B B -->|"Callback ready"| C B -->|"Promise callback"| D E -->|"Monitor"| A E -->|"Check & move"| D E -->|"Check & move"| C
style E fill:#FF9800,color:white style A fill:#4CAF50 style D fill:#2196F3 style C fill:#f44336The Four Components
Section titled “The Four Components”- Call Stack — Executes synchronous code (LIFO)
- Web APIs — Handles async operations (timers, fetch, DOM events)
- Microtask Queue — Promise callbacks,
queueMicrotask() - Macrotask Queue —
setTimeout,setInterval, I/O callbacks
The Event Loop Cycle
Section titled “The Event Loop Cycle”flowchart TD Start["Event Loop Cycle"] Stack["Call Stack Empty?"] Microtask["Process ALL Microtasks"] Render["(Optional) Render"] Macrotask["Process ONE Macrotask"]
Start --> Stack Stack -->|No| Stack Stack -->|Yes| Microtask Microtask -->|"Continue until queue empty"| Microtask Microtask -->|"Empty"| Render Render --> Macrotask Macrotask --> StartSummary
Section titled “Summary”- Event loop monitors call stack and queues
- Processes all microtasks before each macrotask
- Call stack must be empty before processing callbacks
- Render step happens between microtasks and macrotasks