Debouncing
Why Debounce?
Section titled “Why Debounce?”File editors and build tools often trigger many events in rapid succession (save -> write -> write). Debouncing coalesces these bursts into a single event.
Global Debounce
Section titled “Global Debounce”WithDebounce coalesces all events into a single emission after the delay since the last event.
Use case: Build systems, test runners — you want to trigger once after a burst of changes.
// Wait 500ms after the last event, then emit oncewatcher, _ := filewatcher.New(paths, filewatcher.WithDebounce(500*time.Millisecond),)Per-Path Debounce
Section titled “Per-Path Debounce”WithPerPathDebounce debounces each file path independently. Each file gets its own timer.
Use case: Hot reloading where each file triggers its own reload independently.
// Each file emits independently after 500ms of quietwatcher, _ := filewatcher.New(paths, filewatcher.WithPerPathDebounce(500*time.Millisecond),)Comparison
Section titled “Comparison”| Mode | Behavior | Best For |
|---|---|---|
| No debounce | Events emitted immediately | Low-frequency monitoring |
WithDebounce(d) |
All events coalesced into one | Build triggers, test runners |
WithPerPathDebounce |
Each file debounced separately | Hot reload, per-file processing |
Programmatic Debouncer
Section titled “Programmatic Debouncer”For advanced use cases, use the Debouncer and GlobalDebouncer types directly:
// Per-key debouncerdebouncer := filewatcher.NewDebouncer(500 * time.Millisecond)debouncer.Debounce(filewatcher.NewDebounceKey("handler.go"), func() { fmt.Println("handler.go changed")})
// Flush all pending immediatelydebouncer.Flush()
// Stop and clean updebouncer.Stop()
// Global debouncer (ignores key, single timer)global := filewatcher.NewGlobalDebouncer(500 * time.Millisecond)global.Debounce(filewatcher.NewDebounceKey("any"), func() { fmt.Println("something changed")})