Skip to content

Instantly share code, notes, and snippets.

@haleyrc
Last active March 27, 2024 05:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haleyrc/4d7009ff6609afe10bdac0b5ca34b96e to your computer and use it in GitHub Desktop.
Save haleyrc/4d7009ff6609afe10bdac0b5ca34b96e to your computer and use it in GitHub Desktop.
Throttle and debounce implemented in Go
// This gist is a reminder to myself about the differences between throttling and debouncing, inspired by
// https://redd.one/blog/debounce-vs-throttle
//
// A runnable example is available here: https://play.golang.org/p/sADDu829fRa
package main
import (
"fmt"
"time"
)
func main() {
f := func() { fmt.Println("Hello from throttled") }
throttled := throttle(f, time.Second)
callNTimesWithDelay(throttled, 10, 500*time.Millisecond)
g := func() { fmt.Println("Hello from debounced") }
debounced := debounce(g, 500*time.Millisecond)
callNTimesWithDelay(debounced, 10, 100*time.Millisecond)
// Wait to allow the debounce timer to tick
<-time.After(time.Second)
// Call again to see the effect of only calling a debounced function once.
debounced()
<-time.After(time.Second)
}
func throttle(f func(), d time.Duration) func() {
shouldWait := false
return func() {
if !shouldWait {
f()
shouldWait = true
go func() {
<-time.After(d)
shouldWait = false
}()
} else {
fmt.Println("Throttled...")
}
}
}
func debounce(f func(), d time.Duration) func() {
var t *time.Timer
return func() {
if t != nil && !t.Stop() {
<-t.C
}
fmt.Println("Debounced...")
t = time.AfterFunc(d, func() {
f()
t = nil
})
}
}
func callNTimesWithDelay(f func(), n int, delay time.Duration) {
for i := 0; i < n; i++ {
f()
<-time.After(delay)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment