145
Top Answer
Throttle ensures a function runs at most once per time period:
function throttle(func, limit) {
let inThrottle = false;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
// Usage - scroll handler runs at most every 100ms
window.addEventListener('scroll', throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100));
Throttle vs Debounce
| Throttle | Debounce |
|---|---|
| Runs at regular intervals | Runs after user stops |
| Good for: scroll, resize | Good for: search input |
| "At most once per X ms" | "Wait X ms after last call" |
ThrottleMaster