Throttle JavaScript Function Execution for Improved Performance

🚀 JavaScript Simplified Series — Day 39 Yesterday we learned **Debounce**… 👉 Delay execution until user stops But what if you want something different? 🤔 👉 Run function at a **fixed interval** 👉 Even if user keeps triggering it This is where **Throttle** comes in 🔥 --- ## 🔥 Problem Imagine scrolling a page 😵 👉 Scroll event fires 100+ times per second 👉 Function runs again & again 👉 Performance drops 💥 --- ## 🔥 Solution → Throttle --- ## 🔹 What is Throttling? Throttling means: 👉 **Limit function execution** 👉 To once in a fixed time interval --- ## 🔹 Example ```javascript id="th1" function throttle(fn, delay) { let lastCall = 0 return function(...args) { let now = new Date().getTime() if (now - lastCall >= delay) { lastCall = now fn(...args) } } } ``` --- ## 🔹 Usage ```javascript id="th2" function handleScroll() { console.log("Scrolling...") } let throttledScroll = throttle(handleScroll, 1000) // call this on scroll event window.addEventListener("scroll", throttledScroll) ``` 👉 Runs only once every 1 second --- ## 🔍 Debounce vs Throttle 👉 Debounce → run after delay (last call) 👉 Throttle → run at intervals --- ## 🔥 Real Life Example Think of a **water tap 🚰** 👉 You open it → water flows continuously 👉 But flow is controlled 👉 That’s throttle --- ## 🔥 Where is Throttle used? 👉 Scroll events 👉 Resize events 👉 Button spam prevention 👉 Game loops --- ## 🔥 Simple Summary Throttle → limit execution Run → at fixed interval Improve → performance --- ### 💡 Programming Rule **Control how often your code runs. Performance matters.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit NegiHitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance Day 37 → Modules Day 38 → Debounce Day 39 → Throttle Day 40 → Final JavaScript Wrap (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories