Skip to content

Commit

Permalink
timer drained before reseting
Browse files Browse the repository at this point in the history
  • Loading branch information
ratanphayade committed Oct 16, 2020
1 parent b668771 commit 5227fb6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
28 changes: 19 additions & 9 deletions debouncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,27 +61,37 @@ func (d *Debouncer) debounce(ctx context.Context, action Action) {

// value holds the latest input received
value interface{}

timer = time.NewTimer(d.Interval)
)

// trigger the action post the interval duration specified
timer := time.AfterFunc(d.Interval, func() {
if hasEvent {
_ = action(ctx, value)
hasEvent = false
}
})

for {
select {
// if there is an event then reset the timer
// and update the hasEvent to true representing
// to trigger the function once the timer ends
case value = <-d.Input:
hasEvent = true
timer.Reset(d.Interval)

// if the timer ends there is a valid event
// then call the Action provider
case <-timer.C:
if hasEvent {
_ = action(ctx, value)
hasEvent = false
// stop the previous timer
timer.Stop()

// drain the channel if there any event
// else just continue
select {
case <-timer.C:
default:
}

// reset the timer post draining the channel
timer.Reset(d.Interval)

// if the application is being terminated
// then stop the debouncing
case <-ctx.Done():
Expand Down
2 changes: 1 addition & 1 deletion debouncer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestDebounce_Do(t *testing.T) {
d.TriggerAction(i)
}

time.Sleep(500 * time.Millisecond)
time.Sleep(200 * time.Millisecond)
cancel()

assert.Equal(t, 1, counter)
Expand Down

0 comments on commit 5227fb6

Please sign in to comment.