"Understanding JavaScript's Microtasks and Macrotasks"

🌱 Back to Learning JavaScript (Deep Dive Edition) JavaScript’s async behavior isn’t just about the Event Loop it’s powered by two hidden players: Microtasks and Macrotasks. Here’s what I learned after diving deeper. 👉 Microtasks vs Macrotasks We all know the Event Loop keeps JavaScript non-blocking… But what many developers don’t realize is that there are actually two separate queues managing async tasks. 🔹 Microtask Queue Handles: Promise.then(), async/await, queueMicrotask(), MutationObserver Executes immediately after the current synchronous code — before rendering or macrotasks. 🔹 Macrotask Queue (Task Queue) Handles: setTimeout, setInterval, setImmediate, I/O, and fetch callbacks Runs after all microtasks are cleared. Example: console.log("Start"); setTimeout(() => console.log("Macrotask (Timeout)"), 0); Promise.resolve().then(() => console.log("Microtask (Promise)")); console.log("End"); Output: Start End Microtask (Promise) Macrotask (Timeout) 🔎 Something most people don’t know: If microtasks keep queuing themselves (like nested Promises), the browser can’t render causing what’s known as microtask starvation. ✨ Bonus Tip: Rendering happens between macrotasks, not microtasks. That’s why blocking the microtask queue can make your UI feel frozen. 🔑 Takeaway: Knowing how JavaScript schedules microtasks vs macrotasks gives you real control over async behavior, performance, and rendering smoothness. #JavaScript #AsyncProgramming #WebDevelopment #Frontend #EventLoop #JavaScriptInternals #Promises #CodingJourney #LearnInPublic #100DaysOfCode

To view or add a comment, sign in

Explore content categories