Boost Performance with Debouncing & Throttling in JavaScript

💛 Debouncing & Throttling in JavaScript — Boost Performance Like a Pro Ever built: 👉 Search input 👉 Scroll animation 👉 Resize handler 👉 Button click spam …and your app suddenly became slow or laggy? 😵 Because events like: ▪️ scroll ▪️ resize ▪️ mousemove ▪️ keyup can fire 100+ times per second. If your API or heavy logic runs each time… 💥 Performance destroyed. That’s where Debouncing & Throttling save the day. ♦️ The Core Problem 🧠 window.addEventListener("scroll", () => { console.log("Scrolling..."); }); Scroll once → fires hundreds of times 😬 👉 Too many function calls 👉 Too many API requests 👉 UI jank We need control. ♦️ 1️⃣ Debouncing ⏳ 📌 Definition 👉 Execute function only after user stops triggering the event Think: “Wait… let them finish first” Example (Search Bar 🔍) searchInput.addEventListener("keyup", debounce(fetchResults, 500)); User types: r → ra → raj → rajk Without debounce: ❌ 4 API calls With debounce: ✅ 1 API call (after typing stops) 🧠 How It Works Every event: 👉 clears previous timer 👉 sets new timer Only last one survives. ✅ Debounce Polyfill function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } ✅ Real-World Use Cases ✔️ Search suggestions ✔️ Auto-save ✔️ Form validation ✔️ API calls ✔️ Resize events 👉 “Execute after user stops” ♦️ 2️⃣ Throttling 🚦 📌 Definition 👉 Execute function at most once every X milliseconds Think: “Run regularly, but limit frequency” Example (Scroll Tracking 📜) window.addEventListener("scroll", throttle(updateUI, 200)); Scrolling for 5 seconds: Without throttle: ❌ 1000+ calls With throttle: ✅ ~25 calls 🧠 How It Works 👉 First call runs 👉 Next calls ignored until delay passes ✅ Throttle Polyfill function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; fn.apply(this, args); flag = false; setTimeout(() => { flag = true; }, limit); }; } ✅ Real-World Use Cases ✔️ Infinite scroll ✔️ Scroll animations ✔️ Button spam prevention ✔️ Window resize ✔️ Game controls 👉 “Run at controlled intervals” ♦️ Debounce vs Throttle ⚔️ 👉 Debouncing delays execution until events stop firing 👉 Throttling limits execution to fixed intervals Both: ✔️ Reduce unnecessary calls ✔️ Improve performance ✔️ Prevent UI lag ♦️ Mental Model 🧠 Debounce: “Wait till user is done” Throttle: “Slow down the calls” 🥇 Interview One-Liner Debouncing delays execution until events stop firing, while throttling limits execution to fixed intervals — both help optimize performance for high-frequency events like scroll, resize, and input. If this helped, drop a 💛 or share 🔁 Next deep dive 👉 ( Event Propagation ) - Bubbling, Capturing, and Deligation #JavaScript #JSInternals #LearnJavaScript #WebDevelopment  #ProgrammingConcepts #WebDevJourney #BuildInPublic

  • text

To view or add a comment, sign in

Explore content categories