-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdebounce.ts
More file actions
65 lines (62 loc) · 1.8 KB
/
debounce.ts
File metadata and controls
65 lines (62 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
export type DebounceOptions = {
delay?: number;
signal?: AbortSignal;
};
/**
* Creates a debounced function that delays invoking the provided function until after
* the specified delay has elapsed since the last time the debounced function was invoked.
*
* @param fn - The function to debounce
* @param options - Configuration options
* @param options.delay - The number of milliseconds to delay (default: 0)
* @param options.signal - An optional AbortSignal to cancel the debounced function
* @returns A debounced version of the function
*
* @example
* ```ts
* import { debounce } from "./debounce.ts";
* import { delay } from "@std/async/delay";
*
* const saveData = () => console.log("Saving data...");
* const debouncedSave = debounce(() => saveData(), { delay: 100 });
*
* // Multiple calls within 100ms will only trigger one save
* debouncedSave();
* debouncedSave();
* debouncedSave();
*
* // Wait for the debounced function to execute
* await delay(150);
*
* // Cancel via AbortSignal
* const doWork = () => console.log("Doing work...");
* const controller = new AbortController();
* const debouncedFunc = debounce(() => doWork(), {
* delay: 50,
* signal: controller.signal
* });
* debouncedFunc();
* controller.abort(); // Cancels any pending execution
* ```
*/
// deno-lint-ignore no-explicit-any
export function debounce<F extends (...args: any[]) => void>(
fn: F,
{ delay, signal }: DebounceOptions = {},
): F {
let timerId: number | undefined;
const abort = () => {
if (timerId !== undefined) {
clearTimeout(timerId);
timerId = undefined;
}
};
signal?.addEventListener("abort", abort, { once: true });
return ((...args) => {
abort();
timerId = setTimeout(() => {
timerId = undefined;
fn(...args);
}, delay);
}) as F;
}