-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
102 lines (84 loc) · 1.2 KB
/
timer.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"time"
)
type Timer struct {
ticker *time.Ticker
onTick func()
onFinish func()
tl time.Duration
paused bool
}
func createTimer(onTick func(), onFinish func()) *Timer {
return &Timer{
ticker: nil,
onTick: onTick,
onFinish: onFinish,
tl: 0,
paused: false,
}
}
func (t *Timer) pause() {
t.paused = true
}
func (t *Timer) unpause() {
t.paused = false
}
func (t *Timer) toggle() {
if t.paused {
t.unpause()
} else {
t.pause()
}
}
func (t *Timer) set(tm time.Duration) {
t.tl = tm
}
func (t *Timer) create() {
t.ticker = time.NewTicker(1 * time.Second)
}
func (t *Timer) stop() {
if t.ticker != nil {
t.ticker.Stop()
}
t.ticker = nil
}
func (t *Timer) countDown() {
if t.ticker == nil {
t.create()
}
go func() {
for {
select {
case <-t.ticker.C:
if t.paused {
continue
}
t.tl -= time.Second
if t.tl < 0 {
t.ticker.Stop()
t.onFinish()
return
}
t.onTick()
}
}
}()
}
func (t *Timer) countUp() {
if t.ticker == nil {
t.create()
}
go func() {
for {
select {
case <-t.ticker.C:
if t.paused {
continue
}
t.tl += time.Second
t.onTick()
}
}
}()
}