CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

throttle

Creates a function that limits execution of the given function to at most once during each delay interval.

throttle(fn, delay):(...args: TArgs) => void

Parameters

fn(...args: TArgs) => voidrequired

The function to execute at most once during each delay interval.

delaynumberrequired

The minimum time in milliseconds that must pass between executions.

Returns

(...args: TArgs) => void

Returns a function that controls how frequently the original function can execute.

Examples

01

Basic usage

Repeated calls within the delay interval are ignored.

TypeScript
const log = throttle(() => {
  console.log("Executed");
}, 1000);

log();
// Executed

log();
// Ignored

log();
// Ignored
02

Execution after the delay

Once the delay has passed since the last execution, the next call is allowed to execute.

TypeScript
const log = throttle(() => {
  console.log("Executed");
}, 1000);

log();
// Executed

// After 1000ms or more:
log();
// Executed
03

Passing arguments

Arguments from an allowed call are passed directly to the original function.

TypeScript
const logValue = throttle((value: string) => {
  console.log(value);
}, 1000);

logValue("first");
// first

logValue("second");
// Ignored if called before the delay expires
04

Useful for frequent events

throttle can limit how frequently a function responds to frequently triggered events.

TypeScript
const handleScroll = throttle(() => {
  console.log("Scroll handled");
}, 200);

window.addEventListener("scroll", handleScroll);
05

Different arguments between executions

Only arguments from calls that are actually executed are passed to the original function.

TypeScript
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);
// 3
06

No delayed execution

Calls ignored during the delay are not queued or executed later.

TypeScript
const log = throttle(() => {
  console.log("Executed");
}, 1000);

log();
// Executed

log();
// Ignored

// Waiting does not execute the ignored call automatically.
Built with@cyref/js·Official documentation