Last active
February 23, 2023 18:54
-
-
Save benhenryhunter/908de86ff646b46a1727314ae57a0c57 to your computer and use it in GitHub Desktop.
Debouncing function calls in Golang
This file contains 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
// 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