JavaScript Event Loop: Macrotasks vs Microtasks

If you’ve ever logged “A, B, C”… and got “A, C, B” in JavaScript, the event loop just taught you a lesson. ⚙️🧠 Here’s the mental model that stops a lot of “why is my UI stale?” and “why did this run before that?” bugs: Macrotasks (task queue) ✅ - setTimeout/setInterval - DOM events - I/O (in browsers/Node variants) Microtasks (microtask queue) ⚡ - Promise.then/catch/finally - queueMicrotask - MutationObserver Rule of thumb: After a macrotask runs, JS drains ALL microtasks before it picks the next macrotask. So this: console.log(1) setTimeout(()=>console.log(2)) Promise.resolve().then(()=>console.log(3)) console.log(4) prints: 1, 4, 3, 2. Why you should care (real-world): • React/Next.js: state updates and effects can “feel” reordered when you mix timers + promises. Microtasks can run before the browser paints, affecting perceived UI responsiveness 🧩 • Node.js: heavy microtask chains (Promise loops) can starve timers/I/O and make services jittery under load 🚦 • Debugging async: if something “runs too early,” look for a microtask sneaking in. Takeaway: use timers for yielding to the event loop; use microtasks for immediate async sequencing. 🔍 #javascript #nodejs #reactjs #frontend #webperformance #backendengineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories