JavaScript Async Execution: Promise vs setTimeout

⚡ Microtask vs Macrotask Why does Promise.then() run before setTimeout() — even when the delay is 0 ms? Most developers think 0 ms means “immediately”. But JavaScript has a different rule. Here’s what actually happens: 1️⃣ Call Stack executes 2️⃣ All Microtasks run 3️⃣ One Macrotask runs 4️⃣ Repeat And since Promises go to the Microtask Queue, they execute BEFORE Macrotasks like setTimeout(). That’s why: Promise > setTimeout Understanding this small detail can completely change how you debug async code. 💬 Quick Question: What will log first? setTimeout(() => console.log("A"), 0) Promise.resolve().then(() => console.log("B")) Comment your answer 👇 #JavaScript #WebDevelopment #FrontendDeveloper #AsyncProgramming #EventLoop #KeepCoding

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories