Nikhil PC’s Post

🚀 Day 14 – setTimeout Gotcha Think setTimeout runs exactly after the delay? Not quite. 😏 Here’s a classic trap 👇 for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } 👉 What do you expect? 1 2 3 ❌ 👉 What you get: 4 4 4 😲 💥 Why this happens var is function scoped, not block scoped By the time setTimeout executes, the loop is already done i becomes 4, so all callbacks log the same value ✅ Fix #1: Use let for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 1 2 3 ✅ Fix #2: Use Closure for (var i = 1; i <= 3; i++) { ((j) => { setTimeout(() => { console.log(j); }, 1000); })(i); } ✔️ Output: 1 2 3 🧠 Pro Insight (Angular Devs 👇) This matters a LOT when dealing with: async API calls loops with delayed UI updates timers inside components Using let or closures prevents unexpected UI bugs 🐛 ⚡ Takeaway 👉 setTimeout doesn’t pause your loop 👉 It schedules a callback for later 👉 Scope matters more than delay 💬 Have you ever been bitten by this bug? #JavaScript #Angular #WebDevelopment #AsyncJS #Frontend #100DaysOfCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories