forked from bep/debounce
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
56 lines (48 loc) · 1.08 KB
/
example_test.go
File metadata and controls
56 lines (48 loc) · 1.08 KB
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
package debounce_test
import (
"fmt"
"sync/atomic"
"time"
"github.com/floatdrop/debounce/v2"
)
func ExampleNew() {
debouncer := debounce.New(debounce.WithDelay(200 * time.Millisecond))
debouncer.Do(func() { fmt.Println("Hello") })
debouncer.Do(func() { fmt.Println("World") })
time.Sleep(time.Second)
debouncer.Close()
// Output: World
}
func ExampleDebouncer_Func() {
var counter int32
debouncer := debounce.New(debounce.WithDelay(200 * time.Millisecond)).Func(func() {
atomic.AddInt32(&counter, 1)
})
debouncer()
debouncer()
time.Sleep(time.Second)
fmt.Println(atomic.LoadInt32(&counter))
// Output: 1
}
func ExampleChan() {
in := make(chan int)
out := debounce.Chan(in, debounce.WithDelay(200*time.Millisecond))
go func() {
for value := range out {
fmt.Println(value)
}
}()
go func() {
in <- 1
time.Sleep(50 * time.Millisecond)
in <- 2
time.Sleep(50 * time.Millisecond)
in <- 3
time.Sleep(50 * time.Millisecond)
in <- 4
time.Sleep(300 * time.Millisecond) // wait longer than debounce delay
close(in)
}()
time.Sleep(time.Second)
// Output: 4
}