Microtasks vs Macrotasks: Understanding Event Loop Order

🤔 Ever been confused why Promise.then() runs before setTimeout(..., 0)… even though the timeout is “0ms”? That’s microtasks vs macrotasks. 🧠 JavaScript interview question What’s the difference between a microtask and a macrotask, and how does the event loop order them? ✅ Short answer Macrotasks = the “main queue” jobs (timers, events, I/O callbacks) Microtasks = “right-after-this” jobs (Promises, queueMicrotask) After a macrotask finishes, the engine drains ALL microtasks before moving on (and before painting) 🔍 A bit more detail Think of each event loop turn like this: Run one macrotask (e.g. click handler, setTimeout callback) Run all pending microtasks (and if microtasks schedule more microtasks, keep going) Browser can render/paint Next macrotask So microtasks have higher priority than timers. 💻 Example (the classic “wait… why?!”) console.log("start"); setTimeout(() => console.log("timer"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end"); Output: start end promise timer Because: setTimeout schedules a macrotask then() schedules a microtask microtasks run before the next macrotask ⚠️ Small but important Microtasks are powerful… but dangerous if abused. If you keep queuing microtasks in a loop, you can starve rendering and make the UI feel frozen. ⚛️ React tie-in This is why you’ll sometimes see UI not update “immediately” when you chain a lot of Promise work. The browser can’t paint until the microtask queue is done, so heavy microtask chains can make rendering feel delayed. #javascript #webdev #frontend #reactjs #nodejs #eventloop #async #promises #performance #softwareengineering

To view or add a comment, sign in

Explore content categories