-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtimer.js
63 lines (53 loc) · 1.61 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
const MILLISECONDS_IN_SECOND = 1000;
const SECOND_IN_MINUTES = 60;
const POMODORO_END_TIME = 25 * SECOND_IN_MINUTES * MILLISECONDS_IN_SECOND;
module.exports = class Timer {
/**
* Build a new timer
* @param tickCallback to call when tick. Function with 1 argument (countdown).
*/
constructor (pomodoroActivated) {
this.countdown = 0;
this.pomodoroActivated = pomodoroActivated;
}
/**
* Start the timer
* @param initialValue (in millisecond)
*/
start (initialValue = 0, tickCallback = (countdown) => {}, pomodoroCallback = () => {}) {
if(this._timer) {
throw new Error("Timer is already started");
}
this.countdown = initialValue;
this._pomodoroCallback = pomodoroCallback;
this._tickCallback = tickCallback;
this._timer = setInterval(() => {
this._tick();
}, MILLISECONDS_IN_SECOND)
}
/**
* Stop the timer
*/
stop () {
if(this._timer) {
clearInterval(this._timer);
this._timer = undefined;
this._tickCallback = undefined;
}
}
/**
* Stop and reset value of Timer
*/
reset (initialValue = 0) {
this.stop();
this.countdown = initialValue;
}
_tick () {
this.countdown += MILLISECONDS_IN_SECOND;
if((this.countdown >= POMODORO_END_TIME) && this.pomodorActivated) {
this._pomodoroCallback();
} else {
this._tickCallback(this.countdown);
}
}
}