Last active
July 6, 2022 11:59
-
-
Save zhangguanzhang/464f54600ae999e8c73ef6151e0fb877 to your computer and use it in GitHub Desktop.
golang 定时 防抖
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You can edit this code! | |
// Click here and start typing. | |
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
func NewTickerDebouncer(after, tickerTime time.Duration, f func()) func() { | |
d := &debouncer{ | |
after: after, | |
ticker: time.NewTicker(tickerTime), | |
} | |
return func() { | |
d.add(tickerTime, f) | |
} | |
} | |
type debouncer struct { | |
mu sync.Mutex | |
after time.Duration | |
timer *time.Timer | |
ticker *time.Ticker | |
} | |
func (d *debouncer) add(tickerTime time.Duration, f func()) { | |
d.mu.Lock() | |
defer d.mu.Unlock() | |
if d.timer != nil { | |
d.timer.Stop() | |
d.ticker.Reset(tickerTime) | |
} else { | |
go func() { | |
for { | |
<-d.ticker.C | |
f() | |
} | |
}() | |
} | |
d.timer = time.AfterFunc(d.after, func() { | |
d.ticker.Stop() | |
}) | |
} | |
func main() { | |
startAt := time.Now() | |
debounced := NewTickerDebouncer(7*time.Second, time.Second*2, func() { | |
fmt.Printf("triggered after %s\n", time.Now().Sub(startAt)) | |
}) | |
for i := 0; i < 5; i++ { | |
go func() { | |
debounced() | |
}() | |
} | |
<-time.After(time.Second * 10) | |
fmt.Printf("after %s\n", time.Now().Sub(startAt)) | |
go func() { | |
debounced() | |
}() | |
<-time.After(time.Second * 3) | |
fmt.Printf("after %s\n", time.Now().Sub(startAt)) | |
go func() { | |
debounced() | |
}() | |
<-time.After(time.Second * 10) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考 https://github.com/bep/debounce 的延时防抖,但是我的需求是:
上面输出结果是: