JavaScriptHard
JavaScript Event Loop — How It Works (Visual Step-by-Step)
The Event Loop is how JavaScript handles asynchronous operations despite being single-threaded. It continuously checks if the call stack is empty, then moves callbacks from the task queues to the stack for execution.
8 concepts·3 practice problems·Advanced level
Key Concepts
- •JavaScript is single-threaded (one call stack)
- •Web APIs handle async operations (setTimeout, fetch, etc.)
- •Task Queue (Macrotasks): setTimeout, setInterval, I/O
- •Microtask Queue: Promises, queueMicrotask, MutationObserver
- •Microtasks run before the next macrotask
- •Event loop: Stack empty? → Run all microtasks → Run one macrotask → Repeat
Topics Covered
Event LoopHow async JavaScript worksThe Call Stack ExplainedHow JS tracks function executionHow the JS Engine + Web APIs WorkThe components of the JS runtimeTask Queue: MacrotasksQueue for setTimeout, setInterval, I/O callbacksMicrotask Queue: Promises & queueMicrotaskHigher priority than macrotasksOne Event Loop CycleThe complete event loop iterationEvent Loop StarvationWhen tasks block the event loopNode.js Event LoopLibuv phases and async patterns
Practice Problems
Common Mistakes to Avoid
- ×Thinking setTimeout(fn, 0) runs immediately
- ×Not understanding microtask priority over macrotasks
- ×Blocking the event loop with long-running synchronous code
Interview Tips
- ✓Draw the event loop diagram (stack, queues, Web APIs)
- ✓Know the order: sync → microtasks → macrotasks
- ✓Explain why Promises are faster than setTimeout