-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy paththrottle.go
63 lines (54 loc) · 1.03 KB
/
throttle.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
package core
import (
"sync"
"time"
)
// Throttle is a function throttler that takes a function as its argument.
// If ready, it will execute immediately, and it will always wait the specified duration
// between executions. If multiple functions are added within the same execution window,
// only the last function added will be executed.
type Throttle func(f func())
func NewThrottle(period time.Duration) Throttle {
t := &throttle{
period: period,
ready: true,
}
return func(f func()) {
t.add(f)
}
}
type throttle struct {
m sync.Mutex
period time.Duration
ready bool
timer *time.Timer
next func()
}
func (t *throttle) add(f func()) {
t.m.Lock()
ready := t.ready
if ready {
t.ready = false
t.timer = time.AfterFunc(t.period, t.execute)
} else {
t.next = f
}
t.m.Unlock()
if ready {
f()
}
}
func (t *throttle) execute() {
t.m.Lock()
f := t.next
if f != nil {
t.next = nil
t.timer = time.AfterFunc(t.period, t.execute)
} else {
t.ready = true
}
t.m.Unlock()
if f != nil {
f()
}
}