debounce
Delay a function until after a specified time has elapsed since the last call
Usage
The debounce
function helps manage frequent function calls efficiently. It requires two inputs: a delay
time (in milliseconds) and a callback. When you use the function returned by debounce
(a.k.a. the “debounced function”), it doesn’t immediately run your callback. Instead, it waits for the specified delay
.
If called again during this waiting period, it resets the timer. Your source function only runs after the full delay
passes without interruption. This is useful for handling rapid events like keystrokes, ensuring your code responds only after a pause in activity.
Options
leading
When the leading
option is true
, your callback is invoked immediately the very first time the debounced function is called. After that, the debounced function works as if leading
was false
.
Methods
cancel
The cancel
method of the debounced function does two things:
- It cancels any pending invocations of the debounced function.
- It permanently disables the debouncing behavior. All future invocations of the debounced function will immediately invoke your callback.
flush
The flush
method will immediately invoke your callback, regardless of whether the debounced function is currently pending.
isPending
The isPending
method returns true
if there is any pending invocation of the debounced function.