Event Loop (Advanced)
Event Loop Architecture
Call Stack
Where function calls are pushed and executed
LIFO (Last In, First Out)Microtask Queue
For promises and mutation observers
Higher priority than callback queueCallback Queue (Macrotask)
For setTimeout, setInterval, I/O events
Lower priority than microtasksExample 1: Event Loop Execution Order
JavaScript Editor
Event Loop Algorithm
1. Execute all synchronous code (Call Stack) 2. Process all microtasks until queue is empty 3. Render any pending UI updates (if in browser) 4. Process one task from callback queue 5. Repeat from step 2
Example 2: Microtask Starvation
JavaScript Editor
Example 3: Complex Event Loop Scenario
JavaScript Editor
Performance Implications
✅ Best Practices
- Break long tasks into smaller chunks
- Use web workers for CPU-intensive tasks
- Avoid infinite microtask loops
- Use requestIdleCallback for non-urgent work
❌ Common Mistakes
- Blocking the main thread with sync operations
- Creating microtask loops (Promise.resolve().then())
- Not using debounce/throttle for events
- Too many concurrent setTimeout callbacks
Exercise: Predict the Output
JavaScript Editor