forked from offlegacy/event-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebounce.ts
More file actions
92 lines (80 loc) · 2.38 KB
/
Copy pathdebounce.ts
File metadata and controls
92 lines (80 loc) · 2.38 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Debounce configuration options
*/
export interface DebounceConfig {
/** Delay in milliseconds */
delay: number;
/** Execute on the leading edge (default: false) */
leading?: boolean;
/** Execute on the trailing edge (default: true) */
trailing?: boolean;
}
/**
* Debounced function interface with cancel and flush methods
*/
export interface DebouncedFunction<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
cancel: () => void;
flush: () => void;
}
/**
* Creates a debounced version of the provided function
*
* @param fn - The function to debounce
* @param options - Debounce configuration
* @returns Debounced function with cancel and flush methods
*/
export function debounce<T extends (...args: any[]) => any>(fn: T, options: DebounceConfig): DebouncedFunction<T> {
const { delay, leading = false, trailing = true } = options;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let lastArgs: Parameters<T> | null = null;
let hasInvokedLeading = false;
const debouncedFn = (...args: Parameters<T>) => {
lastArgs = args;
// Leading edge execution
if (leading && !hasInvokedLeading && timeoutId === null) {
hasInvokedLeading = true;
fn(...args);
}
// Clear existing timeout
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
// Set new timeout for trailing edge
timeoutId = setTimeout(() => {
if (trailing && lastArgs !== null) {
// Execute trailing edge if:
// 1. Only trailing is enabled, OR
// 2. Both leading and trailing are enabled (separate call)
if (!leading || (leading && trailing)) {
fn(...lastArgs);
}
}
// Reset state
timeoutId = null;
hasInvokedLeading = false;
lastArgs = null;
}, delay);
};
// Cancel method - clears timeout and resets state
debouncedFn.cancel = () => {
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
hasInvokedLeading = false;
lastArgs = null;
};
// Flush method - executes immediately if there's a pending call
debouncedFn.flush = () => {
if (timeoutId !== null && lastArgs !== null) {
clearTimeout(timeoutId);
fn(...lastArgs);
// Reset state
timeoutId = null;
hasInvokedLeading = false;
lastArgs = null;
}
};
return debouncedFn as DebouncedFunction<T>;
}