-
Notifications
You must be signed in to change notification settings - Fork 12
/
Timer.js
72 lines (62 loc) · 1.16 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
export function Timer() {
let _timer = 0
let _defaultTimer
let _interval
let _events = new Map()
function start(time) {
stop()
if (time) {
setTimer(time)
}
if (_timer === _defaultTimer && _events.get("secondsUpdated")) {
_events.get("secondsUpdated")()
}
_interval = setTimeout(() => {
_timer -= 1
if (_events.get("secondsUpdated")) {
_events.get("secondsUpdated")()
}
if (_timer <= 0) {
stop()
if (_events.get("targetAchieved")) {
_events.get("targetAchieved")()
}
} else {
start()
}
}, 1000)
}
function stop() {
clearInterval(_interval)
}
function reset() {
if (_events.get("reset")) {
_events.get("reset")()
}
_timer = _defaultTimer
stop()
start()
}
function setTimer(time) {
_timer = time
_defaultTimer = time
}
function on(event, fn) {
_events.set(event, fn)
}
function removeAllEventListeners() {
_events.clear()
}
function getTime() {
return _timer
}
return {
setTimer,
reset,
start,
on,
removeAllEventListeners,
stop,
getTime
}
}