-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelay.mjs
80 lines (60 loc) · 1.74 KB
/
Delay.mjs
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
/**
* Asynchronous delay that can be canceled
*/
export default class Delay {
/**
* indicates if the delay is currently running
*
* @return {boolean} True if running, False otherwise.
*/
isRunning() {
return this.started && !this.ended;
}
/**
* Cancel the delay. Will stall your code at the position you are waiting for the delay to
* resolve. Wont stall your process since it is just a promise that is never going to be
* resolved.
*/
cancel() {
clearTimeout(this.timeout);
}
/**
* Cancel the delay, continue execution
*
* @param {*} value value to return when resolving
*/
cancelAndResolve(value) {
if (!this.started) throw new Error('Cannot cancel delay, it was never started!');
this.resolve(value);
}
/**
* Cancel the delay, continue execution with an exception
*
* @param {Error} err error to throw
*/
cancelAndReject(err) {
if (!this.started) throw new Error('Cannot cancel delay, it was never started!');
this.reject(err);
}
/**
* Delay the execution n milliseconds
*
* @param {number} msecs milliseconds to wait
* @return {Promise} undefined
*/
async wait(msecs) {
if (this.started) {
throw new Error('Cannot start delay, it was started already!');
}
this.started = true;
const promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
this.timeout = setTimeout(() => {
this.ended = true;
this.resolve();
}, msecs);
return promise;
}
}