File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 11package utils
22
3+ import (
4+ "sync/atomic"
5+ "time"
6+ )
7+
38func CompareSlices (a , b []any ) bool {
49 if len (a ) != len (b ) {
510 return false
@@ -31,3 +36,32 @@ func CompareStringSlices(a, b []string) bool {
3136func 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+ }
You can’t perform that action at this time.
0 commit comments