throttle() function
throttle function creates a throttled version of a function that can only be invoked at most once per specified time period. Unlike debounce, throttle ensures the function is called at regular intervals during continuous invocations, rather than waiting for a pause. This is useful for rate-limiting expensive operations like scroll handlers, window resizing, or API calls.
The throttled function supports leading and trailing edge execution: - leading: Execute immediately on the first call - trailing: Execute at the end of the throttle period with the latest arguments
The throttled function includes a .cancel() method to cancel any pending trailing invocations.
Signature:
typescript
declare function throttle<T extends (...args: any[]) => void>(func: T, wait: number, options?: {
leading: boolean;
trailing: boolean;
}): ((...args: Parameters<T>) => void) & {
cancel: () => void;
};Example
ts
// Basic usage (default options - both leading and trailing)
const throttled = throttle((val: number) => {
console.log('val', val);
}, 1000);
throttled(1); // immediately logs: val 1
throttled(2); // ignored
throttled(3); // ignored
// After 1000ms, logs: val 3 (trailing call with latest args)
// Leading edge only (useful for preventing rapid repeated actions)
const throttled2 = throttle((val: number) => {
console.log('val', val);
}, 1000, { leading: true, trailing: false });
throttled2(1); // immediately logs: val 1
throttled2(2); // ignored
throttled2(3); // ignored
// After 1000ms, nothing happens
// Trailing edge only (useful for batch processing)
const throttled3 = throttle((val: number) => {
console.log('val', val);
}, 1000, { leading: false, trailing: true });
throttled3(1); // delayed
throttled3(2); // delayed
throttled3(3); // delayed
// After 1000ms, logs: val 3 (only the latest value)
// Canceling pending throttled invocations
const throttled4 = throttle((val: number) => {
console.log('val', val);
}, 1000);
throttled4(1); // immediately logs: val 1
throttled4(2);
throttled4(3);
throttled4.cancel(); // cancels pending trailing invocation
// Nothing happens after 1000ms
// Real-world use case - throttling scroll events
const handleScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 200);
window.addEventListener('scroll', handleScroll);
// The handler will fire immediately on first scroll,
// then at most once every 200ms during continuous scrolling,
// and once more after scrolling stops (trailing edge)