Throttle Function
Limits function execution to once per specified time interval
Throttle limits function execution to a regular interval, regardless of how many times the event triggers. Unlike debounce which waits for the end, throttle executes the function immediately then ignores subsequent calls during the interval. Ideal for scroll, resize, or mousemove events.
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Usage
const handleScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100);
window.addEventListener('scroll', handleScroll);