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
package debounce
import (
"sync"
"time"
)
const DefaultDelay = 5 * time.Second
type Debounce struct {
delay time.Duration
fn func()
mu sync.Mutex
timer *time.Timer
stopped bool
}
func New(delay time.Duration, fn func()) *Debounce {
if delay <= 0 {
delay = DefaultDelay
}
return &Debounce{delay: delay, fn: fn}
}
func (d *Debounce) Mark() {
d.mu.Lock()
defer d.mu.Unlock()
if d.stopped || d.timer != nil {
return
}
d.timer = time.AfterFunc(d.delay, func() {
d.mu.Lock()
d.timer = nil
stopped := d.stopped
d.mu.Unlock()
if !stopped {
d.fn()
}
})
}
func (d *Debounce) Stop() {
d.mu.Lock()
defer d.mu.Unlock()
d.stopped = true
if d.timer != nil {
d.timer.Stop()
d.timer = nil
}
}