Skip to content

Instantly share code, notes, and snippets.

@benhenryhunter
Last active February 23, 2023 18:54
Show Gist options
  • Save benhenryhunter/908de86ff646b46a1727314ae57a0c57 to your computer and use it in GitHub Desktop.
Save benhenryhunter/908de86ff646b46a1727314ae57a0c57 to your computer and use it in GitHub Desktop.
Debouncing function calls in Golang
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Hello, 世界")
iChan := make(chan any)
go debounce(iChan, 3*time.Second, print)
count := 0
for {
if count > 8 {
return
}
count++
iChan <- count
time.Sleep(1 * time.Second)
fmt.Println(count)
}
}
func print(i any) {
fmt.Println("called", i)
}
func debounce(c chan any, timeout time.Duration, b func(any)) {
a := <-c
b(a)
lastCall := time.Now()
for {
a := <-c
if time.Since(lastCall) < timeout {
timer := time.NewTimer(timeout - time.Since(lastCall))
called := false
for {
select {
case newA := <-c:
a = newA
case <-timer.C:
b(a)
lastCall = time.Now()
called = true
}
if called {
break
}
}
} else {
lastCall = time.Now()
b(a)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment