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
rust
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread;
Aggregating metrics across threads in Rust
concurrency
shared-state
mutex
Intermediate
7 steps
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
java
public class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 steps
rust
use std::sync::{mpsc, Arc, Mutex}; use std::thread; use std::time::Duration;
Building a thread pool in Rust
concurrency
channels
thread-pool
Advanced
9 steps
typescript
import { Pipe, PipeTransform, ChangeDetectorRef, NgZone, OnDestroy } from '@angular/core'; @Pipe({ name: 'timeAgo',
A self-refreshing timeAgo pipe in Angular
impure-pipe
change-detection
timers
Advanced
10 steps
go
package cache import ( "container/list"
Building a generic LRU cache in Go
lru-cache
generics
linked-list
Intermediate
8 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.