Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/markdown-language-features/src/util/async.ts
3292 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
export interface ITask<T> {
7
(): T;
8
}
9
10
export class Delayer<T> {
11
12
public defaultDelay: number;
13
private _timeout: any; // Timer
14
private _cancelTimeout: Promise<T | null> | null;
15
private _onSuccess: ((value: T | PromiseLike<T> | undefined) => void) | null;
16
private _task: ITask<T> | null;
17
18
constructor(defaultDelay: number) {
19
this.defaultDelay = defaultDelay;
20
this._timeout = null;
21
this._cancelTimeout = null;
22
this._onSuccess = null;
23
this._task = null;
24
}
25
26
dispose() {
27
this._doCancelTimeout();
28
}
29
30
public trigger(task: ITask<T>, delay: number = this.defaultDelay): Promise<T | null> {
31
this._task = task;
32
if (delay >= 0) {
33
this._doCancelTimeout();
34
}
35
36
if (!this._cancelTimeout) {
37
this._cancelTimeout = new Promise<T | undefined>((resolve) => {
38
this._onSuccess = resolve;
39
}).then(() => {
40
this._cancelTimeout = null;
41
this._onSuccess = null;
42
const result = this._task?.() ?? null;
43
this._task = null;
44
return result;
45
});
46
}
47
48
if (delay >= 0 || this._timeout === null) {
49
this._timeout = setTimeout(() => {
50
this._timeout = null;
51
this._onSuccess?.(undefined);
52
}, delay >= 0 ? delay : this.defaultDelay);
53
}
54
55
return this._cancelTimeout;
56
}
57
58
private _doCancelTimeout(): void {
59
if (this._timeout !== null) {
60
clearTimeout(this._timeout);
61
this._timeout = null;
62
}
63
}
64
}
65
66