Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/merge-conflict/src/delayer.ts
3296 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 completionPromise: Promise<T> | 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.completionPromise = null;
22
this.onSuccess = null;
23
this.task = null;
24
}
25
26
public trigger(task: ITask<T>, delay: number = this.defaultDelay): Promise<T> {
27
this.task = task;
28
if (delay >= 0) {
29
this.cancelTimeout();
30
}
31
32
if (!this.completionPromise) {
33
this.completionPromise = new Promise<T | undefined>((resolve) => {
34
this.onSuccess = resolve;
35
}).then(() => {
36
this.completionPromise = null;
37
this.onSuccess = null;
38
const result = this.task!();
39
this.task = null;
40
return result;
41
});
42
}
43
44
if (delay >= 0 || this.timeout === null) {
45
this.timeout = setTimeout(() => {
46
this.timeout = null;
47
this.onSuccess!(undefined);
48
}, delay >= 0 ? delay : this.defaultDelay);
49
}
50
51
return this.completionPromise;
52
}
53
54
public forceDelivery(): Promise<T> | null {
55
if (!this.completionPromise) {
56
return null;
57
}
58
this.cancelTimeout();
59
const result = this.completionPromise;
60
this.onSuccess!(undefined);
61
return result;
62
}
63
64
public isTriggered(): boolean {
65
return this.timeout !== null;
66
}
67
68
public cancel(): void {
69
this.cancelTimeout();
70
this.completionPromise = null;
71
}
72
73
private cancelTimeout(): void {
74
if (this.timeout !== null) {
75
clearTimeout(this.timeout);
76
this.timeout = null;
77
}
78
}
79
}
80
81