aboutsummaryrefslogtreecommitdiff
path: root/internal/watcher/debounce.go
blob: b2961bda9db66f54b4752c9e650077fa2245b123 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package watcher

import (
	"context"
	"time"
)

// notify schedules a debounced notification.
//
// Multiple filesystem events collapse into a single callback.
func (w *Watcher) notify() {
	if w.config.OnChange == nil {
		return
	}

	select {
	case w.debounce <- struct{}{}:
	default:
	}
}

func (w *Watcher) debounceLoop(ctx context.Context) {
	if w.config.OnChange == nil {
		return
	}

	timer := time.NewTimer(time.Hour)

	if !timer.Stop() {
		select {
		case <-timer.C:
		default:
		}
	}

	var pending bool

	for {
		select {
		case <-ctx.Done():
			return

		case <-w.debounce:
			pending = true

			if !timer.Stop() {
				select {
				case <-timer.C:
				default:
				}
			}

			timer.Reset(w.config.Debounce)

		case <-timer.C:
			if pending {
				pending = false
				w.config.OnChange()
			}
		}
	}
}