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 axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
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.