-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.js
62 lines (52 loc) · 1.41 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
const TimerState = {
STOPPED: 'Stopped', PAUSED: 'Paused', RUNNING: 'Running',
};
export class Timer {
constructor() {
this.state = TimerState.STOPPED;
this.lastUpdate = 0;
this.elapsedTime = 0;
}
isRunning() {
return this.state === TimerState.RUNNING;
}
isPaused() {
return this.state === TimerState.PAUSED;
}
start() {
this.state = TimerState.RUNNING;
this.lastUpdate = this.getTimeNow();
this.elapsedTime = 0;
}
pause() {
this.state = TimerState.PAUSED;
this.updateElapsedTime();
}
resume() {
this.lastUpdate = this.getTimeNow();
this.state = TimerState.RUNNING;
}
stop() {
this.state = TimerState.STOPPED;
this.lastUpdate = 0;
this.elapsedTime = 0;
}
updateElapsedTime() {
if (this.isRunning()) {
const currentTime = this.getTimeNow();
let timeElapsed = (currentTime - this.lastUpdate) / 1000.0;
this.elapsedTime = Math.max(this.elapsedTime + timeElapsed, 0);
this.lastUpdate = currentTime;
if (this.elapsedTime <= 0) {
this.state = TimerState.STOPPED;
this.elapsedTime = 0;
}
}
}
setElapsedTime(elapsedTime) {
this.elapsedTime = elapsedTime;
}
getTimeNow() {
return new Date().getTime();
}
}