go 37 lines · 6 steps

Building a debouncer in Go

A small struct that delays a function until calls stop arriving, resetting the timer on each trigger.

Explained by highlit
1package debounce
2 
3import (
4 "sync"
5 "time"
6)
7 
8type Debouncer struct {
9 mu sync.Mutex
10 delay time.Duration
11 timer *time.Timer
12}
13 
14func New(delay time.Duration) *Debouncer {
15 return &Debouncer{delay: delay}
16}
17 
18func (d *Debouncer) Trigger(fn func()) {
19 d.mu.Lock()
20 defer d.mu.Unlock()
21 
22 if d.timer != nil {
23 d.timer.Stop()
24 }
25 
26 d.timer = time.AfterFunc(d.delay, fn)
27}
28 
29func (d *Debouncer) Cancel() {
30 d.mu.Lock()
31 defer d.mu.Unlock()
32 
33 if d.timer != nil {
34 d.timer.Stop()
35 d.timer = nil
36 }
37}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Debouncing collapses a burst of rapid calls into a single execution after a quiet period.
  2. 2Resetting a timer on each event means only the final call survives the delay.
  3. 3Guarding shared timer state with a mutex keeps concurrent triggers safe.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a debouncer in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code