Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/util/common/debounce.ts
13397 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
type DebounceState = {
7
timer: any;
8
reject: (reason?: any) => void;
9
};
10
11
/**
12
* Debouncer class for async code.
13
*
14
* Implements "trailing" debouncing as described here:
15
* https://css-tricks.com/debouncing-throttling-explained-examples/#aa-debounce
16
*
17
* For a given instance of this class, at most one call to `debounce` can be
18
* in progress at a time. A subsequent call will trigger rejection of the promise returned
19
* by the previous call.
20
*/
21
export class Debouncer {
22
private state: DebounceState | undefined;
23
24
/**
25
* Wait for the specified number of milliseconds, then resolve.
26
* Rejects if another call is made to `debounce` on this object in the meantime.
27
*/
28
public async debounce(ms: number): Promise<void> {
29
if (this.state) {
30
clearTimeout(this.state.timer);
31
this.state.reject();
32
this.state = undefined;
33
}
34
return new Promise<void>((resolve, reject) => {
35
this.state = {
36
timer: setTimeout(() => resolve(), ms),
37
reject,
38
};
39
});
40
}
41
}
42
43
/** Debounce function for sync functions */
44
export function debounce<T extends (...args: any[]) => any>(
45
ms: number,
46
callback: T
47
): (...args: Parameters<T>) => Promise<ReturnType<T>> {
48
let timer: any | undefined;
49
50
return (...args: Parameters<T>) => {
51
if (timer) {
52
clearTimeout(timer);
53
}
54
return new Promise<ReturnType<T>>(resolve => {
55
timer = setTimeout(() => {
56
const returnValue = callback(...args) as ReturnType<T>;
57
resolve(returnValue);
58
}, ms);
59
});
60
};
61
}
62
63