Skip to content

Instantly share code, notes, and snippets.

@zhangguanzhang
Last active July 6, 2022 11:59
Show Gist options
  • Save zhangguanzhang/464f54600ae999e8c73ef6151e0fb877 to your computer and use it in GitHub Desktop.
Save zhangguanzhang/464f54600ae999e8c73ef6151e0fb877 to your computer and use it in GitHub Desktop.
golang 定时 防抖
// 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)
}
@zhangguanzhang
Copy link
Author

参考 https://github.com/bep/debounce 的延时防抖,但是我的需求是:

  1. 一条狗,拍它狗头开始,会有5分钟的活跃时间
  2. 狗活跃期间,每隔5秒叫一次
  3. 无论何时拍它狗头,最后一次拍头后过5分钟,狗就睡觉并不叫了

上面输出结果是:

triggered after 2.005864s
triggered after 4.0076892s
triggered after 6.0159339s
after 10.0150096s
triggered after 12.0237643s
after 13.0189366s
triggered after 15.0292168s
triggered after 17.020204s
triggered after 19.0198119s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment