Skip to content

throttle

The throttle function limits how frequently a function can be executed, ensuring it is called at most once every defined time interval.

Syntax

typescript
throttle(callback, wait, options?)

Parameters

NameTypeDescription
callbackFunctionFunction to be executed in a controlled manner.
waitnumberMinimum interval (in milliseconds) between function executions.
optionsobject(Optional) Additional settings: { leading, trailing, maxWait }.

options object

NameTypeDescription
leadingbooleanExecutes at the start of the interval (default: true).
trailingbooleanExecutes at the end of the interval (default: true).
maxWaitnumberMaximum time without execution, even with continuous calls.

Return Value

TypeDescription
FunctionThrottled function with cancel() and flush() methods.

Examples

typescript
const throttledFn = throttle(() => console.log('Executed!'), 1000);
window.addEventListener('resize', throttledFn);

// Cancel pending calls
throttledFn.cancel();

// Force immediate execution
throttledFn.flush();

Notes

  • Throws a TypeError if the callback is not a function.
  • Useful for optimizing high-frequency events like scroll, resize, etc.

References

Released under the MIT License.