Description
throttle
returns a new function that, when called repeatedly, guarantees func
is executed at most once every
limit
milliseconds. Subsequent calls within the wait period are ignored until the timer resets.
Code Byte
export function throttle<T extends (...args: any[]) => void>(
func: T,
limit: number = 300
): (...args: Parameters<T>) => void {
let inThrottle: boolean;
return function(this: any, ...args: Parameters<T>) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
Use Cases:
- Scroll handlers: Limit calls to a handler during rapid scrolling.
- Window resize: Prevent heavy recalculations from firing more than once per interval.
- Mouse movement: Reduce updates when tracking cursor position continuously.
- Button clicks: Enforce a minimum delay between successive click handlers.
Example Usage:
import { throttle } from './throttle.util';
// 1) Throttled scroll event
const onScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 200);
window.addEventListener('scroll', onScroll);
// 2) Throttled mousemove for tooltip updates
const onMouseMove = throttle((e: MouseEvent) => {
tooltip.setPosition(e.clientX, e.clientY);
}, 100);
document.addEventListener('mousemove', onMouseMove);