GoDebouncer
Like JavaScript's debounce, but for the backend
go get -u github.com/vnteamopen/godebouncer
package main
import (
"fmt"
"time"
"github.com/vnteamopen/godebouncer"
)
func main() {
debouncer := godebouncer.New(5 * time.Second).WithTriggered(func() {
fmt.Println("Trigger") // Triggered func will be called after 5 seconds from last SendSignal().
})
fmt.Println("Action 1")
debouncer.SendSignal()
time.Sleep(1 * time.Second)
fmt.Println("Action 2")
debouncer.SendSignal()
// After 5 seconds, the trigger will be called.
// Previous `SendSignal()` will be ignored to trigger the triggered function.
<-debouncer.Done()
}
Run Actions Before Sending Signal
Run a special action before the debouncer sends signal with debouncer.Do(specialFunc)
. The debouncer first invokes specialFunc
, then sends signal to invoke triggered function after wait
time.
Control Debouncer Lifecycle
Cancel debouncer from invoking the triggered function at any time with debouncer.Cancel()
. Send a signal to the debouncer again when you want to restart it.
Update Debouncer After Sending Signal
Debouncer allows replacing the triggered function and the timer after the signal was sent. The new timer take effect in the next SendSignal()
.
Notify the Caller When Triggered Func Finishes
Debouncer allows sending a signal via the Done()
channel to the caller to let it knows the triggered func has been executed successfully.