Overview
Thedebounce function creates a debounced version of a callback that delays its execution until after a specified delay has elapsed since the last time it was invoked. This is useful for rate-limiting events like user input, window resizing, or scroll events.
Import
Signature
Parameters
The function to debounce.
The number of milliseconds to delay. If
undefined, the callback is invoked immediately.Optional configuration object.
The maximum number of milliseconds to wait before invoking
callbackFn again, regardless of debounce delay.Return Value
A debounced function with the following properties and methods:
Call the debounced function with the same parameters as the original callback.
Call with an override object as the second parameter:
{ $delay: number } to dynamically change the delay.Cancels all pending invocations (both main timeout and maxWait timeout).
Cancels only the maxWait timeout while keeping the main debounce timeout active.
Usage Examples
Basic Debounce
With maxWait Option
Dynamic Delay Override
Cancelling Debounced Functions
Common Use Cases
- Search Input: Delay API calls until the user stops typing
- Window Resize: Limit recalculations during window resize events
- Form Auto-save: Save form data after user stops editing
- Scroll Events: Reduce the frequency of scroll event handlers
Notes
- The debounced function maintains the same signature as the original callback
- Stored parameters are cleared after invocation or cancellation
- The
maxWaitoption ensures the callback is invoked at least once within the specified timeframe - Use
cancel()to prevent any pending invocations - Use
cancelMaxWait()to cancel only the max wait timeout while keeping the debounce active