Skip to content

debounce

The debounce function limits how often a function can be executed, delaying its call until a period of inactivity is reached.

Syntax

typescript
debounce(callback, wait?, options?)

Parameters

NameTypeDescription
callbackFunctionFunction to be executed in a controlled manner.
waitnumber(Optional) Wait time in milliseconds (default: 300).
optionsobject(Optional) { leading, trailing, maxWait } for advanced control.

options object

NameTypeDescription
leadingbooleanExecutes at the start of the interval (default: false).
trailingbooleanExecutes at the end of the interval (default: true).
maxWaitnumberMaximum time without execution (in ms).

Return Value

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

Examples

typescript
const debounced = debounce(() => console.log('Executed!'), 500, { leading: true });
debounced();
debounced(); // Only the first call executes immediately

Notes

  • Throws an error if both leading and trailing are false.
  • Useful for optimizing frequent events like typing or resizing.

References

Released under the MIT License.