Visualizing the JavaScript Event Loop and Microtasks
From synchronous code to microtask queues.
Understanding the order of execution in JavaScript is critical when orchestrating async operations.
Task Queues Breakdown
- Call Stack: Executes synchronous operations until empty.
- Microtask Queue: Resolved promises (
Promise.then),queueMicrotask, andMutationObserver. Emptied completely after each stack frame. - Macrotask Queue:
setTimeout,setInterval,setImmediate, and I/O. Executed one per tick.
console.log('1')
setTimeout(() => console.log('2'), 0)
Promise.resolve().then(() => console.log('3'))
console.log('4')
// Output: 1, 4, 3, 2