samber / lo

💥 A Lodash-style Go library based on Go 1.18+ Generics (map, filter, contains, find...)
https://pkg.go.dev/github.com/samber/lo
MIT License
17.89k stars 821 forks source link

Proposal: Add throttle #396

Open adrianrudnik opened 11 months ago

adrianrudnik commented 11 months ago

Based on lodash _.throttle.

Use case: I want to publish an update to a websocket at most any given time.Duration. So basically like the already existing debounce, but limiting with delay, not delaying until end.

Working with onboard functions, I came up with something like this:

delay := 500 * time.Millisecond

internalInvoke, cancel = lo.NewDebounceBy(delay, func(key int64, count int) {
    // .... do stuff
})

throttle = func() {
    internalInvoke(time.Now().Round(delay).UnixNano())
}

So in the end, calling throttle() will put the rounded nano time in a bucket for debounce and that bucket will be triggered after delay is no longer inside the same rounding range.

Not sure what to do with cancel though.

Lee-Minjea commented 9 months ago

I was looking for 'throttle' too.

Hi @samber, if there is no PR working on this currently. I would like to make one.

and Please pardon my absence of acknowledge on twitter, I don't have twitter account.