Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions debounce.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,13 @@ func New(after time.Duration, options ...Option) func(fn func()) {
// Creating timer and immediately stop it, so there will be always allocated Timer
d.timer = time.AfterFunc(NoLimitWait, func() {
d.mu.Lock()
if d.calls == 0 {
d.mu.Unlock()
return // MaxCalls or MaxWait reached, call can be dropped
}
d.calls = 0
d.mu.Unlock()

d.fn()
})
d.timer.Stop()
Expand Down Expand Up @@ -117,6 +122,7 @@ func (d *debouncer) debouncedCall(fn func()) {
// If the function has been called more than the limit, or if the wait time
// has exceeded the limit, execute the function immediately.
if d.callLimitReached() || d.timeLimitReached() {
d.timer.Stop() // Stop the timer to prevent it from firing later
d.calls = 0
fn := d.fn
go fn() // Execute outside mutex to avoid blocking
Expand Down
8 changes: 8 additions & 0 deletions debounce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,14 @@ func TestWithMaxCalls(t *testing.T) {
t.Errorf("Expected 1 call, got %d", called)
}
mu.Unlock()

// Should not be called after it
time.Sleep(110 * time.Millisecond) // Small delay to allow execution
mu.Lock()
if called != 1 {
t.Errorf("Expected 1 call, got %d", called)
}
mu.Unlock()
}

func TestWithMaxCallsNoLimit(t *testing.T) {
Expand Down
Loading