-
Notifications
You must be signed in to change notification settings - Fork 630
/
Copy pathActionScheduler.js
98 lines (75 loc) · 2.55 KB
/
ActionScheduler.js
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* Copyright (c) 2018-present, Evgeny Nadymov
*
* This source code is licensed under the GPL v.3.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
class ActionScheduler {
constructor(actionCallback, cancelCallback) {
this.actions = new Map();
this.actionCallback = actionCallback;
this.cancelCallback = cancelCallback;
}
add = (key, timeout, action, cancel) => {
if (this.actions.has(key)) {
return false;
}
let expire = new Date();
expire.setMilliseconds(expire.getMilliseconds() + timeout);
this.actions.set(key, { expire: expire, action: action, cancel: cancel });
if (this.timerId) {
clearTimeout(this.timerId);
}
this.setTimeout();
return true;
};
invoke = async key => {
const item = this.actions.get(key);
if (!item) return;
this.actions.delete(key);
await this.actionCallback({ key: key, action: item.action, cancel: item.cancel });
if (item.action) await item.action();
if (this.timerId) {
clearTimeout(this.timerId);
}
this.setTimeout();
};
remove = key => {
const item = this.actions.get(key);
if (!item) return;
this.actions.delete(key);
this.cancelCallback({ key: key, action: item.action, cancel: item.cancel });
if (item.cancel) item.cancel();
if (this.timerId) {
clearTimeout(this.timerId);
}
this.setTimeout();
};
setTimeout = () => {
let now = new Date();
let timeout = 1000000;
for (let [key, value] of this.actions) {
let actionTimeout = value.expire - now;
if (actionTimeout < timeout) timeout = actionTimeout;
if (timeout < 0) timeout = 0;
}
if (timeout < 1000000) {
this.timerId = setTimeout(this.handleTimer, timeout);
}
};
handleTimer = () => {
let now = new Date();
let expired = [];
for (let [key, value] of this.actions) {
let actionTimeout = value.expire - now;
if (actionTimeout <= 0) expired.push({ key: key, value: value });
}
for (let item of expired) {
this.actions.delete(item.key);
this.actionCallback({ key: item.key, action: item.value.action, cancel: item.value.cancel });
if (item.value.action) item.value.action();
}
this.setTimeout();
};
}
export default ActionScheduler;