1.38.0throttle
Creates a function that limits execution of the given function to at most once during each delay interval.
throttle(fn, delay):(...args: TArgs) => voidParameters
fn(...args: TArgs) => voidrequiredThe function to execute at most once during each delay interval.
delaynumberrequiredThe minimum time in milliseconds that must pass between executions.
Returns
(...args: TArgs) => voidReturns a function that controls how frequently the original function can execute.
Examples
Basic usage
Repeated calls within the delay interval are ignored.
const log = throttle(() => {
console.log("Executed");
}, 1000);
log();
// Executed
log();
// Ignored
log();
// IgnoredExecution after the delay
Once the delay has passed since the last execution, the next call is allowed to execute.
const log = throttle(() => {
console.log("Executed");
}, 1000);
log();
// Executed
// After 1000ms or more:
log();
// ExecutedPassing arguments
Arguments from an allowed call are passed directly to the original function.
const logValue = throttle((value: string) => {
console.log(value);
}, 1000);
logValue("first");
// first
logValue("second");
// Ignored if called before the delay expiresUseful for frequent events
throttle can limit how frequently a function responds to frequently triggered events.
const handleScroll = throttle(() => {
console.log("Scroll handled");
}, 200);
window.addEventListener("scroll", handleScroll);Different arguments between executions
Only arguments from calls that are actually executed are passed to the original function.
const logValue = throttle((value: number) => {
console.log(value);
}, 1000);
logValue(1);
// 1
logValue(2);
// Ignored if called before the delay expires
// After the delay:
logValue(3);
// 3No delayed execution
Calls ignored during the delay are not queued or executed later.
const log = throttle(() => {
console.log("Executed");
}, 1000);
log();
// Executed
log();
// Ignored
// Waiting does not execute the ignored call automatically.