Last active
August 29, 2015 14:04
-
-
Save amullins83/07f9130597f44528150f to your computer and use it in GitHub Desktop.
Generic Debounce in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.