2024-04-25 14:56:13 +03:00
|
|
|
# debounce
|
|
|
|
|
|
|
|
Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds
|
|
|
|
have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel`
|
|
|
|
method to cancel any pending execution.
|
|
|
|
|
|
|
|
## Signature
|
|
|
|
|
|
|
|
```typescript
|
2024-06-14 02:04:05 +03:00
|
|
|
function debounce<F extends (...args: any[]) => void>(
|
|
|
|
func: F,
|
|
|
|
debounceMs: number,
|
|
|
|
options?: DebounceOptions
|
|
|
|
): F & { cancel: () => void };
|
2024-04-25 14:56:13 +03:00
|
|
|
```
|
|
|
|
|
2024-06-04 11:19:26 +03:00
|
|
|
### Parameters
|
2024-04-25 14:56:13 +03:00
|
|
|
|
2024-06-05 02:05:56 +03:00
|
|
|
- `func` (`F`): The function to debounce.
|
2024-06-14 02:04:05 +03:00
|
|
|
- `debounceMs` (`number`): The number of milliseconds to delay.
|
|
|
|
- `options` (`DebounceOptions`, optional): An options object.
|
|
|
|
- `signal` (`AbortSignal`, optional): An optional `AbortSignal` to cancel the debounced function.
|
2024-04-25 14:56:13 +03:00
|
|
|
|
|
|
|
### Returns
|
|
|
|
|
2024-06-05 02:05:56 +03:00
|
|
|
(`F & { cancel: () => void }`): A new debounced function with a `cancel` method.
|
2024-04-25 14:56:13 +03:00
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
2024-06-14 02:04:05 +03:00
|
|
|
### Basic Usage
|
|
|
|
|
2024-04-25 14:56:13 +03:00
|
|
|
```typescript
|
|
|
|
const debouncedFunction = debounce(() => {
|
|
|
|
console.log('Function executed');
|
|
|
|
}, 1000);
|
|
|
|
|
|
|
|
// Will log 'Function executed' after 1 second if not called again in that time
|
|
|
|
debouncedFunction();
|
|
|
|
|
|
|
|
// Will not log anything as the previous call is canceled
|
|
|
|
debouncedFunction.cancel();
|
|
|
|
```
|
2024-06-14 02:04:05 +03:00
|
|
|
|
|
|
|
### Using with an AbortSignal
|
|
|
|
|
|
|
|
```typescript
|
|
|
|
const controller = new AbortController();
|
|
|
|
const signal = controller.signal;
|
|
|
|
const debouncedWithSignalFunction = debounce(
|
|
|
|
() => {
|
|
|
|
console.log('Function executed');
|
|
|
|
},
|
|
|
|
1000,
|
|
|
|
{ signal }
|
|
|
|
);
|
|
|
|
|
|
|
|
// Will log 'Function executed' after 1 second if not called again in that time
|
|
|
|
debouncedWithSignalFunction();
|
|
|
|
|
|
|
|
// Will cancel the debounced function call
|
|
|
|
controller.abort();
|
|
|
|
```
|