Throttling is a technique used to limit the number of times a function is executed over time, even if an event is triggered repeatedly.
🔹 Purpose of Throttling:
To improve performance by ensuring a function executes at most once every X milliseconds, regardless of how often it's triggered.
🔸 Use Cases:
- Scroll event tracking
- Resize window event
- Repeated button clicks
- API polling
🔸 Example: Throttling Function
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
lastCall = now;
func(...args);
}
};
}
// Example usage
const logScroll = () => console.log("Scrolling...");
window.addEventListener("scroll", throttle(logScroll, 1000));
🧠 Even if you scroll continuously, logScroll will only run once every 1000ms.
🔸 Difference from Debouncing:
| Throttling | Debouncing |
|---|---|
| Executes function at intervals | Executes after pause |
| Useful for rate limiting | Useful for delaying execution |