mirror of
https://github.com/duke-git/lancet.git
synced 2025-10-05 07:26:51 +08:00
feat: add Debounce function
This commit is contained in:
@@ -7,6 +7,7 @@ package function
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -84,22 +85,44 @@ func Delay(delay time.Duration, fn any, args ...any) {
|
||||
}
|
||||
|
||||
// Debounced creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.
|
||||
// Deprecated: Use Debounce function instead.
|
||||
// Play: https://go.dev/play/p/absuEGB_GN7
|
||||
func Debounced(fn func(), duration time.Duration) func() {
|
||||
// Catch programming error while constructing the closure
|
||||
mustBeFunction(fn)
|
||||
func Debounced(fn func(), delay time.Duration) func() {
|
||||
debouncedFn, _ := Debounce(fn, delay)
|
||||
return debouncedFn
|
||||
}
|
||||
|
||||
timer := time.NewTimer(duration)
|
||||
timer.Stop()
|
||||
// Debounce creates a debounced version of the provided function.
|
||||
// Play: todo
|
||||
func Debounce(fn func(), delay time.Duration) (debouncedFn func(), cancelFn func()) {
|
||||
var (
|
||||
timer *time.Timer
|
||||
mu sync.Mutex
|
||||
)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
<-timer.C
|
||||
go fn()
|
||||
debouncedFn = func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
return func() { timer.Reset(duration) }
|
||||
timer = time.AfterFunc(delay, func() {
|
||||
fn()
|
||||
})
|
||||
}
|
||||
|
||||
cancelFn = func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
return debouncedFn, cancelFn
|
||||
}
|
||||
|
||||
// Schedule invoke function every duration time, util close the returned bool channel.
|
||||
|
Reference in New Issue
Block a user