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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing collapses a burst of rapid calls into a single execution after a quiet period.
- 2Resetting a timer on each event means only the final call survives the delay.
- 3Guarding shared timer state with a mutex keeps concurrent triggers safe.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-debouncer-in-go-explained-go-1289/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.