Debounce Rapid Function Calls

Coalesce bursts of events into one delayed function call using time.AfterFunc and a mutex-protected timer per debouncer.

GoResilience

Code

gosnippet
50 lines
package main

import (
	"fmt"
	"sync"
	"time"
)

type Debouncer struct {
	mu    sync.Mutex
	delay time.Duration
	timer *time.Timer
}

func NewDebouncer(delay time.Duration) *Debouncer {
	return &Debouncer{delay: delay}
}

func (d *Debouncer) Do(fn func()) {
	d.mu.Lock()
	defer d.mu.Unlock()
	if d.timer != nil {
		d.timer.Stop()
	}
	d.timer = time.AfterFunc(d.delay, fn)
}

func (d *Debouncer) Stop() {
	d.mu.Lock()
	defer d.mu.Unlock()
	if d.timer != nil {
		d.timer.Stop()
	}
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	debounce := NewDebouncer(50 * time.Millisecond)
	start := time.Now()
	for index := 0; index < 5; index++ {
		debounce.Do(func() {
			fmt.Println("fired after", time.Since(start).Round(time.Millisecond))
			wg.Done()
		})
		time.Sleep(10 * time.Millisecond)
	}
	wg.Wait()
}

Inside the snippet

Everything happens inside the functions NewDebouncer, Do, Stop and main.

Iteration happens inside for index := 0; index < 5; index++ — everything outside it runs once. The function registers its cleanup up front with defer, so no exit path forgets it.

Caveats

  • The environment needs no preparation beyond having the interpreter or compiler.

Using it

The main signature reads func NewDebouncer(delay time.Duration) *Debouncer

Running the file prints labeled results such as fired after — each operation’s effect is visible in the output.

The demo flow inside main is NewDebouncer and Do — run the file to see it end to end.

Key statements worth quoting

func (d *Debouncer) Do(fn func()) {
d.mu.Lock()
defer d.mu.Unlock()
if d.timer != nil {
d.timer.Stop()
}
d.timer = time.AfterFunc(d.delay, fn)
}
func NewDebouncer(delay time.Duration) *Debouncer {
return &Debouncer{delay: delay}
}
func (d *Debouncer) Stop() {
d.mu.Lock()
defer d.mu.Unlock()
if d.timer != nil {
d.timer.Stop()
}
}

Interactive Tools for This Topic

FAQ

What does Debounce Rapid Function Calls print when run?
The script runs standalone; its 1 labeled outputs include `fired after`.