The function type
The function to throttle
The number of milliseconds to throttle invocations to
A throttled function with a cancel method
import { throttle } from '@consumidor-positivo/ts-utils';
// Basic usage - limit a function to run at most once every 500ms
const throttledScroll = throttle(() => {
console.log('Scroll event handled');
}, 500);
window.addEventListener('scroll', throttledScroll);
// With arguments and return value
const throttledCalculate = throttle((a: number, b: number) => {
console.log('Calculating...');
return a + b;
}, 300);
// Cancel any pending invocation
setTimeout(() => {
throttledCalculate.cancel();
console.log('Throttled function canceled');
}, 1000);
Creates a throttled function that only invokes the provided function at most once per specified interval.
The throttled function comes with a cancel method to cancel delayed invocations.
This utility is useful for limiting the rate at which a function can fire, such as during window resize or scroll events, API calls, or other intensive operations.