You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
931 B

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. package common
  2. import (
  3. "time"
  4. "sync"
  5. )
  6. /* Debouncer */
  7. type Debouncer struct {
  8. Ch chan struct{}
  9. quit chan struct{}
  10. dur time.Duration
  11. mtx sync.Mutex
  12. timer *time.Timer
  13. }
  14. func NewDebouncer(dur time.Duration) *Debouncer {
  15. var timer *time.Timer
  16. var ch = make(chan struct{})
  17. var quit = make(chan struct{})
  18. var mtx sync.Mutex
  19. fire := func() {
  20. go func() {
  21. select {
  22. case ch <- struct{}{}:
  23. case <-quit:
  24. }
  25. }()
  26. mtx.Lock(); defer mtx.Unlock()
  27. timer.Reset(dur)
  28. }
  29. timer = time.AfterFunc(dur, fire)
  30. return &Debouncer{Ch:ch, dur:dur, quit:quit, mtx:mtx, timer:timer}
  31. }
  32. func (d *Debouncer) Reset() {
  33. d.mtx.Lock(); defer d.mtx.Unlock()
  34. d.timer.Reset(d.dur)
  35. }
  36. func (d *Debouncer) Stop() bool {
  37. d.mtx.Lock(); defer d.mtx.Unlock()
  38. close(d.quit)
  39. return d.timer.Stop()
  40. }