Skip to content

Commit 3e60d24

Browse files
authored
feat: throttle (#72)
1 parent c99a1d4 commit 3e60d24

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

utils/utils.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package utils
22

3+
import (
4+
"sync/atomic"
5+
"time"
6+
)
7+
38
func CompareSlices(a, b []any) bool {
49
if len(a) != len(b) {
510
return false
@@ -31,3 +36,32 @@ func CompareStringSlices(a, b []string) bool {
3136
func Ptr[T any](v T) *T {
3237
return &v
3338
}
39+
40+
type Throttle struct {
41+
lastCall time.Time
42+
limit time.Duration
43+
timer atomic.Pointer[time.Timer]
44+
}
45+
46+
func NewThrottle(limit time.Duration) *Throttle {
47+
return &Throttle{limit: limit}
48+
}
49+
50+
func (t *Throttle) Do(f func()) {
51+
now := time.Now()
52+
if now.Sub(t.lastCall) >= t.limit {
53+
t.lastCall = now
54+
f()
55+
if old := t.timer.Swap(nil); old != nil {
56+
old.Stop()
57+
}
58+
} else {
59+
lastFunc := f
60+
if old := t.timer.Swap(time.AfterFunc(t.limit-now.Sub(t.lastCall), func() {
61+
t.lastCall = time.Now()
62+
lastFunc()
63+
})); old != nil {
64+
old.Stop()
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)