-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanaged-timer.js
More file actions
68 lines (58 loc) · 1.26 KB
/
managed-timer.js
File metadata and controls
68 lines (58 loc) · 1.26 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
63
64
65
66
67
68
class ManagedTimer {
constructor(callback, ms, recurring, st, ct, si, ci) {
this.callback = callback;
this.recurring = recurring;
this.ms = ms;
this.si = si;
this.ci = ci;
this.st = st;
this.ct = ct;
this.elapsed = 0;
}
start() {
if (this.firstStarted) {
throw new Error("Timer already started.");
}
this.firstStarted = Date.now();
this._start();
}
reset() {
this.cancel();
this.firstStarted = null;
}
_start() {
const setMethod = this.recurring ? this.si : this.st;
this.clearMethod = this.recurring ? this.ci : this.ct;
this.startedAt = Date.now();
const handle = setMethod(() => {
this._invoke();
}, this.ms);
this.clear = this.clearMethod.bind(this, handle);
}
_invoke() {
this.callback();
this.startedAt = Date.now();
this.elapsed = 0;
}
cancel() {
if (this.clear) {
this.clear();
}
}
pause() {
this.elapsed += Date.now() - this.startedAt;
this.clear();
}
unpause() {
this.startedAt = Date.now();
const handle = this.st(() => {
console.log("test");
this._invoke();
if (this.recurring) {
this._start();
}
}, this.ms - this.elapsed);
this.clear = this.ct.bind(this, handle);
}
}
module.exports = ManagedTimer;