Force execution in tickAndDebounce after debounceTime

This commit is contained in:
Martin Boehm 2018-04-03 22:09:46 +02:00
parent 26de7eb384
commit 7d6a9ae663

View File

@ -255,6 +255,7 @@ func main() {
func tickAndDebounce(tickTime time.Duration, debounceTime time.Duration, input chan struct{}, f func()) { func tickAndDebounce(tickTime time.Duration, debounceTime time.Duration, input chan struct{}, f func()) {
timer := time.NewTimer(tickTime) timer := time.NewTimer(tickTime)
var firstDebounce time.Time
Loop: Loop:
for { for {
select { select {
@ -266,12 +267,21 @@ Loop:
if !ok { if !ok {
break Loop break Loop
} }
// debounce for debounceTime if firstDebounce.IsZero() {
timer.Reset(debounceTime) firstDebounce = time.Now()
}
// debounce for up to debounceTime period
// afterwards execute immediately
if firstDebounce.Add(debounceTime).After(time.Now()) {
timer.Reset(debounceTime)
} else {
timer.Reset(0)
}
case <-timer.C: case <-timer.C:
// do the action and start the loop again // do the action and start the loop again
f() f()
timer.Reset(tickTime) timer.Reset(tickTime)
firstDebounce = time.Time{}
} }
} }
} }