-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.js
72 lines (61 loc) · 1.46 KB
/
timer.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
const { EventEmitter} = require("events");
const INTERVAL = 50;
const STATE = {
NEW: "new",
PENDING: "pending",
COMPLETED: "completed",
};
module.exports = class Timer extends EventEmitter{
constructor(totalTime, callback) {
super();
this.count = 0;
this.timeLeft = totalTime;
this.callback = callback;
this.state = STATE.NEW;
this.intervalId = null;
}
start() {
if(this.isNew()) {
this.tickOrComplete();
} else {
return false;
}
return true;
}
isNew() {
return this.state === STATE.NEW;
}
isComplete() {
return this.state === STATE.COMPLETED;
}
hasTimeToTick () {
return this.timeLeft >= INTERVAL;
}
tick() {
this.intervalId = setInterval(() => {
this.timeLeft -= INTERVAL;
this.count += 1;
this.emit("tick");
this.continueTickOrComplete();
}, INTERVAL);
}
continueTickOrComplete() {
if(!this.hasTimeToTick()) {
clearInterval(this.intervalId);
this.complete();
}
}
complete() {
setTimeout(() => {
this.emit("complete", this.count);
this.callback(this.count);
}, this.timeLeft);
}
tickOrComplete() {
if(this.hasTimeToTick()) {
this.tick();
} else {
this.complete();
}
}
};