Throttling
Throttling is a technique used to limit the number of times a function can be executed over a certain period. Unlike debouncing, which delays execution until a pause occurs, throttling ensures that the function is executed at a regular interval.
1. The Concept
Think of a machine gun. No matter how fast you pull the trigger, it can only fire bullets at a specific rate (e.g., 10 rounds per second). Throttling enforces a maximum frequency of execution.
2. Implementation
A basic throttle function uses a flag to indicate if the function is currently in a "cooldown" period.
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
}
}
3. Practical Use Case: Infinite Scroll
When checking if the user has scrolled to the bottom of the page to load more content, the scroll event fires hundreds of times per second. Throttling ensures the check only happens, say, every 200ms.
function checkScrollPosition() {
console.log('Checking scroll position...');
// Logic to check if near bottom
}
const throttledScroll = throttle(checkScrollPosition, 200);
window.addEventListener('scroll', throttledScroll);
4. Throttling vs. Debouncing
- Throttling: "Execute at a steady rate." (e.g., every 100ms while scrolling).
- Debouncing: "Execute only after activity stops." (e.g., wait 300ms after the last keystroke).
programming/javascript/vanilla/javascript programming/javascript/vanilla/debouncing programming/throttling-pattern