Help
How the Event Loop Works
The JavaScript event loop is a mechanism that handles asynchronous operations:
- Call Stack: Executes functions in LIFO order (Last In, First Out)
- Web APIs: Handle async operations like setTimeout, fetch, etc.
- Callback Queue: Stores callbacks ready to execute
- Event Loop: Moves callbacks from queue to stack when stack is empty
The event loop continuously checks: if the call stack is empty, it pushes the first callback from the queue onto the stack.
Microtasks vs Macrotasks
Microtasks (higher priority):
- Promise callbacks (.then, .catch, .finally)
- queueMicrotask()
- MutationObserver
Macrotasks (regular queue):
- setTimeout, setInterval
- setImmediate (Node.js)
- I/O operations
All microtasks execute before the next macrotask!
Understanding setTimeout(fn, 0)
A common misconception is that setTimeout(fn, 0) executes immediately.
Reality: It schedules the callback to run after:
- All current synchronous code completes
- All microtasks (Promises) complete
- The event loop moves it from queue to stack
This is why console.log runs before setTimeout callbacks even with 0ms delay!
Using This Visualizer
- Choose Example: Click an example button to load pre-made code
- Start: Click "Start" to auto-execute step by step
- Step: Use "Step" button to manually control execution
- Speed: Adjust slider to control auto-execution speed
- Watch: Observe items moving between stack, APIs, and queue
- Console: See output as code executes
- Custom: Write your own code to visualize