-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.js
59 lines (50 loc) · 1.55 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
class Timer {
constructor(durationInput, startButton, pauseButton, callbacks) {
this.durationInput = durationInput
this.startButton = startButton
this.pauseButton = pauseButton
if (callbacks) {
this.onStart = callbacks.onStart
this.onTick = callbacks.onTick
this.onCompleted = callbacks.onCompleted
}
this.startButton.addEventListener('click', this.start)
this.pauseButton.addEventListener('click', this.pause)
}
start = () => {
if (this.onStart) {
this.onStart(this.timeRemaining)
}
this.tick()
this.interval = setInterval(this.tick, 20)
}
pause = () => {
if (this.onCompleted) {
this.onCompleted()
}
clearInterval(this.interval)
console.log('paused')
}
tick = () => {
if (this.onTick) {
this.onTick(this.timeRemaining)
}
console.log("ticked")
if (this.timeRemaining <= 0) {
this.pause()
console.log("paused from tick")
} else {
// const timeRemaining = this.timeRemain
// this.durationInput.value = timeRemaining - 1
/* This is the appropriate place to invoke onTick from callback */
this.timeRemaining -= 0.02
console.log(this.timeRemaining)
}
}
get timeRemaining() {
return parseFloat(this.durationInput.value)
}
set timeRemaining(time) {
this.durationInput.value = time.toFixed(2)
}
}