-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutable.go
108 lines (87 loc) · 2.17 KB
/
mutable.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
103
104
105
106
107
108
package debounce
import (
"sync"
"time"
)
// NewMutable returns a debounced function like New, but it allows callback
// function f to be changed, as a new callback function is passed to each
// invocation of the debounced function.
//
// The returned cancel function can be used to cancel any pending invocation of
// f, but is not required to be called, so can be ignored if not needed.
//
// Only the very last f passed to the debounced function is called when the
// delay expires and the callback function is invoked. Previous f values are
// discarded.
//
// Both debounced and cancel functions are safe for concurrent use in
// goroutines, and can both be called multiple times.
func NewMutable(wait time.Duration) (debounced func(f func()), cancel func()) {
var mux sync.Mutex
var fn func()
timer := stoppedTimer(func() {
mux.Lock()
defer mux.Unlock()
go fn()
})
debounced = func(f func()) {
mux.Lock()
defer mux.Unlock()
fn = f
timer.Reset(wait)
}
cancel = func() {
mux.Lock()
defer mux.Unlock()
timer.Stop()
}
return debounced, cancel
}
// NewMutableWithMaxWait is a combination of NewMutable and NewWithMaxWait.
//
// When either of the wait or maxWait timers expire, the last f passed to the
// debounced function is called.
//
// The returned cancel function can be used to cancel any pending invocation of
// f, but is not required to be called, so can be ignored if not needed.
//
// Both debounced and cancel functions are safe for concurrent use in
// goroutines, and can both be called multiple times.
func NewMutableWithMaxWait(
wait, maxWait time.Duration,
) (debounced func(f func()), cancel func()) {
var mux sync.Mutex
var fn func()
var timer *time.Timer
var maxTimer *time.Timer
cb := func() {
mux.Lock()
defer mux.Unlock()
if fn == nil {
return
}
go fn()
timer.Stop()
maxTimer.Stop()
fn = nil
}
timer = stoppedTimer(cb)
maxTimer = stoppedTimer(cb)
debounced = func(f func()) {
mux.Lock()
defer mux.Unlock()
timer.Reset(wait)
if fn == nil {
maxTimer.Reset(maxWait)
}
fn = f
}
cancel = func() {
mux.Lock()
defer mux.Unlock()
timer.Stop()
maxTimer.Stop()
fn = nil
}
return debounced, cancel
}