forked from bep/debounce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebounce_time.go
75 lines (62 loc) · 1.36 KB
/
debounce_time.go
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
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright © 2024 Jon Friesen <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package debounce
import (
"sync"
"time"
)
var now = time.Now
// NewDebounceByDuration returns a debounced function that takes another function as its argument.
// This function will be called at the given interval, but no more than the max duration
// from the first call.
func NewDebounceByDuration(interval, maxDuration time.Duration) func(f func()) {
d := &durationDebouncer{
interval: interval,
maxDuration: maxDuration,
}
return func(f func()) {
d.add(f)
}
}
type durationDebouncer struct {
mu sync.Mutex
interval time.Duration
maxDuration time.Duration
timer *time.Timer
firstCall bool
startTime time.Time
}
func (d *durationDebouncer) add(f func()) {
d.mu.Lock()
defer d.mu.Unlock()
now := now()
if !d.firstCall {
d.firstCall = true
d.startTime = now
}
if d.timer != nil {
d.timer.Stop()
}
remainingDuration := d.maxDuration - time.Since(d.startTime)
if remainingDuration <= 0 {
d.reset()
f()
return
}
d.timer = time.AfterFunc(d.interval, func() {
d.mu.Lock()
defer d.mu.Unlock()
f()
d.reset()
})
}
func (d *durationDebouncer) reset() {
d.firstCall = false
if d.timer != nil {
d.timer.Stop()
d.timer = nil
}
d.startTime = time.Time{}
}