⚡ Throttling in JavaScript Explained with Examples
Have you ever wondered how to control how often a function runs when triggered frequently — like on scroll, resize, or button click? That's where Throttling in JavaScript comes in.
📌 What is Throttling?
Throttling is a technique used to limit the number of times a function gets called over time. Instead of calling the function every time an event fires, it ensures the function executes only once every specified interval.
resize, scroll tracking, infinite scroll, button spam protection, etc.
🧠 How Throttling Works
Let’s say an event is triggered 50 times per second. With throttling, you can restrict the callback to run only once every 300ms or any interval you decide.
🛠️ Simple Example of Throttling
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}
}
const logScroll = () => console.log("Scroll event at", new Date().toLocaleTimeString());
window.addEventListener('scroll', throttle(logScroll, 1000));
✅ Benefits of Throttling
- Improves performance by reducing function calls
- Prevents layout thrashing and jank in UI
- Helps manage API calls or data fetching efficiently
🤔 Throttling vs Debouncing
Both are rate-limiting techniques:
- Throttling: Ensures function runs at most once in a given interval.
- Debouncing: Delays the function until after the last event in a series.
🔚 Conclusion
Throttling is essential when dealing with high-frequency event handlers. It helps you build efficient and responsive applications by avoiding performance bottlenecks.
📚 Recommended Reading:
- Debouncing in JavaScript Explained
- setTimeout vs setInterval: What's the Difference?
- requestAnimationFrame vs setTimeout

Comments
Post a Comment