The Event Loop Trap: Why Your Code Runs Out of Order

⚡ “The Event Loop Trap — Why Your Code Runs Out of Order” You write this 👇 console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Expected output? Start → Timeout → Promise → End Reality? Start → End → Promise → Timeout 👉 That’s the event loop catching you off guard. 🧠 Why This Happens JavaScript is single‑threaded but non‑blocking. The event loop orchestrates execution: Call Stack → Runs synchronous code first. Microtask Queue → Promises, await, queueMicrotask. Macrotask Queue → setTimeout, setInterval, DOM events. Loop → Sync → Microtasks → ONE Macrotask → Repeat 🔁 🚀 Angular Example In Angular 21–22 apps: You poll APIs every few seconds. You rely on signals + OnPush for reactivity. If you assume setTimeout(fn, 0) runs immediately, your UI may render stale data or lag behind user actions. Promise.resolve().then(() => console.log('Microtask')); setTimeout(() => console.log('Macrotask'), 0); Output: Microtask → Macrotask Angular’s signal‑first runtime depends on this ordering for predictable updates. ⚖️ Golden Rule (Never Forget) 1️⃣ Sync code first 2️⃣ Then all microtasks 3️⃣ Then one macrotask 🔁 Repeat 🔥 Why This Matters Debugging async issues Avoiding race conditions Predictable UI rendering Understanding why logs look “out of order” What output did you expect before reading this? 😅 #JavaScript #EventLoop #Angular #Signals #OnPush #Frontend #Performance #WebDevelopment #CleanCode #AsyncProgramming

  • No alternative text description for this image

This is were most of the developers make mistake

To view or add a comment, sign in

Explore content categories