forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebouncer.ts
More file actions
38 lines (30 loc) · 1.02 KB
/
Copy pathdebouncer.ts
File metadata and controls
38 lines (30 loc) · 1.02 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
export type AsyncFunction<T extends any[]> = (
...args: [...T, AbortSignal]
) => Promise<void>;
export class Debouncer<T extends any[]> {
private timeoutId?: ReturnType<typeof setTimeout>;
private activeAbortController?: AbortController;
constructor(private wait: number) {}
debounce = async (func: AsyncFunction<T>, ...args: T) => {
// Abort the previous promise immediately
this.cancel();
this.timeoutId = setTimeout(async () => {
try {
this.activeAbortController = new AbortController();
// Pass the signal to the async function, assuming it supports it
await func(...args, this.activeAbortController.signal);
this.activeAbortController = undefined;
} catch (error) {}
}, this.wait);
};
cancel = () => {
if (this.activeAbortController) {
this.activeAbortController.abort();
this.activeAbortController = undefined;
}
if (this.timeoutId !== undefined) {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
};
}