-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamicAsyncInterval.js
More file actions
62 lines (48 loc) · 1.44 KB
/
DynamicAsyncInterval.js
File metadata and controls
62 lines (48 loc) · 1.44 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const AsyncInterval = require("interval-promise");
function asyncInterval(promise, ms) {
const self = this;
this._shouldStop = false;
this._interval = AsyncInterval(async (iteration, stop) => {
if (self._shouldStop) {
stop();
this._shouldStop = undefined;
this._interval = undefined;
} else {
await promise();
}
}, ms);
this.destroy = function () {
self._shouldStop = true;
};
}
function DynamicAsyncInterval(promise, interval) {
const self = this;
this._promise = promise;
this._interval = new asyncInterval(promise, interval);
this.reschedule = function (interval) {
// if no interval entered, use the interval passed in on creation
if (!interval) interval = self._interval;
if (self._interval) self._interval.destroy();
self._interval = new asyncInterval(self._promise, interval);
};
this.clear = function () {
if (self._interval) {
self._interval.destroy();
self._interval = undefined;
}
};
this.destroy = function () {
if (self._interval) {
self._interval.destroy();
}
self._promise = undefined;
self._interval = undefined;
};
}
function dynamicAsyncInterval(promise, ms) {
if (typeof promise !== "function") throw new Error("promise/callback needed");
if (typeof ms !== "number")
throw new Error("interval (in milliseconds) needed");
return new DynamicAsyncInterval(promise, ms);
}
module.exports = dynamicAsyncInterval;