tendermint/common/debounce.go

49 lines
807 B
Go
Raw Normal View History

2014-06-17 01:28:43 -07:00
package common
import (
2014-07-01 14:50:24 -07:00
"sync"
"time"
2014-06-17 01:28:43 -07:00
)
/* Debouncer */
type Debouncer struct {
2014-07-01 14:50:24 -07:00
Ch chan struct{}
quit chan struct{}
dur time.Duration
mtx sync.Mutex
timer *time.Timer
2014-06-17 01:28:43 -07:00
}
func NewDebouncer(dur time.Duration) *Debouncer {
2014-07-01 14:50:24 -07:00
var timer *time.Timer
var ch = make(chan struct{})
var quit = make(chan struct{})
var mtx sync.Mutex
fire := func() {
go func() {
select {
case ch <- struct{}{}:
case <-quit:
}
}()
mtx.Lock()
defer mtx.Unlock()
timer.Reset(dur)
}
timer = time.AfterFunc(dur, fire)
return &Debouncer{Ch: ch, dur: dur, quit: quit, mtx: mtx, timer: timer}
2014-06-17 01:28:43 -07:00
}
func (d *Debouncer) Reset() {
2014-07-01 14:50:24 -07:00
d.mtx.Lock()
defer d.mtx.Unlock()
d.timer.Reset(d.dur)
2014-06-17 01:28:43 -07:00
}
func (d *Debouncer) Stop() bool {
2014-07-01 14:50:24 -07:00
d.mtx.Lock()
defer d.mtx.Unlock()
close(d.quit)
return d.timer.Stop()
2014-06-17 01:28:43 -07:00
}