Skip to content

Instantly share code, notes, and snippets.

@amullins83
Last active August 29, 2015 14:04
Show Gist options
  • Save amullins83/07f9130597f44528150f to your computer and use it in GitHub Desktop.
Save amullins83/07f9130597f44528150f to your computer and use it in GitHub Desktop.
Generic Debounce in Go
package main
import (
"fmt"
"time"
)
func debounce(interval time.Duration, f func(argList []interface{})) func([]interface{}) {
timer := &time.Timer{}
return func(argList []interface{}) {
timer.Stop()
timer = time.AfterFunc(interval, func() {
f(argList)
})
}
}
func main() {
spammyChan := make(chan int, 10)
debouncedCostlyOperation := debounce(300*time.Millisecond, func(argList []interface{}) {
switch t := argList[0].(type) {
case int:
fmt.Println("*****************************")
fmt.Println("* DOING A COSTLY OPERATION! *")
fmt.Println("*****************************")
fmt.Println("In case you were wondering, the value passed to this function is", argList[0].(int))
fmt.Println("We could have more args to our \"compiled\" debounced function too, if we wanted.")
default:
fmt.Printf("Invalid argument type %T\n", t)
}
})
go func() {
for {
select {
case spam := <-spammyChan:
fmt.Println("received a send on a spammy channel - might be doing a costly operation if not for debounce")
argList := make([]interface{}, 1)
argList[0] = interface{}(spam)
debouncedCostlyOperation(argList)
default:
}
}
}()
for i := 0; i < 10; i++ {
spammyChan <- i
}
time.Sleep(500 * time.Millisecond)
}
@amullins83
Copy link
Author

Inspired by Nathan LeClaire's blog. While []interface{} is generally frowned-upon for its inherent lack of type safety, it does allow generic programming.

@amullins83
Copy link
Author

Quick update: the debounced function now uses a type switch to avoid runtime errors. The debounce function itself cannot perform this check. It is the responsibility of code passed in to verify the parameter list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment