debouncer.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package helper
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // Debouncer handles debounced execution of functions
  7. type Debouncer struct {
  8. timer *time.Timer
  9. mutex sync.Mutex
  10. duration time.Duration
  11. isFirst bool
  12. }
  13. // NewDebouncer creates a new debouncer with the specified duration
  14. func NewDebouncer(duration time.Duration) *Debouncer {
  15. return &Debouncer{
  16. duration: duration,
  17. isFirst: true,
  18. }
  19. }
  20. // Trigger executes the callback function with debouncing logic
  21. // For the first call, it executes immediately
  22. // For subsequent calls, it debounces with the configured duration
  23. func (d *Debouncer) Trigger(callback func()) {
  24. d.mutex.Lock()
  25. defer d.mutex.Unlock()
  26. if d.isFirst {
  27. d.isFirst = false
  28. go callback() // Execute immediately for first call
  29. return
  30. }
  31. // Stop existing timer if any
  32. if d.timer != nil {
  33. d.timer.Stop()
  34. }
  35. // Set new timer for debounced execution
  36. d.timer = time.AfterFunc(d.duration, func() {
  37. go callback()
  38. })
  39. }
  40. // Stop cancels any pending debounced execution
  41. func (d *Debouncer) Stop() {
  42. d.mutex.Lock()
  43. defer d.mutex.Unlock()
  44. if d.timer != nil {
  45. d.timer.Stop()
  46. d.timer = nil
  47. }
  48. }