Documentation
¶
Overview ¶
Package debounce provides a generic debounce utility for channels. It allows throttling the rate of emitted values using optional delay and/or limit mechanisms.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Chan ¶
Chan wraps an input channel and returns a debounced output channel. Debouncing behavior is defined by the combination of WithDelay and WithLimit:
- WithDelay delays value emission until no new values are received for `delay`.
- WithLimit limits the number of delay resets (i.e., bouncing) before emission is forced.
If both are set, a value will be emitted after either the `delay` passes without new input, or after the delay has been reset `limit` times.
If delay is 0, the function returns the input channel unmodified.
Example ¶
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
Types ¶
type Debouncer ¶
type Debouncer struct {
// contains filtered or unexported fields
}
func New ¶
Creates new Debouncer instance that will call provided functions with debounce.
Example ¶
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 (*Debouncer) Close ¶
func (d *Debouncer) Close()
Closes underlying channel in Debouncer instance.
func (*Debouncer) Do ¶
func (d *Debouncer) Do(f func())
Do adds function f to be executed with debounce.
func (*Debouncer) Func ¶
func (d *Debouncer) Func(f func()) func()
Func returns func wrapper of function f, that will execute function f with debounce on call.
Example ¶
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