Last active
July 26, 2022 18:54
-
-
Save wfgilman/dc8a5823bb95ef73abe09fe4653ada4e to your computer and use it in GitHub Desktop.
Debouncer Example in Go
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
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func debounce(f func(), delay string) func() { | |
var t *time.Timer | |
count := 0 | |
return func() { | |
count += 1 | |
fmt.Printf("Debounce called %d times\n", count) | |
duration, _ := time.ParseDuration(delay) | |
if t != nil { | |
t.Stop() | |
} | |
t = time.AfterFunc(duration, f) | |
} | |
} | |
func main() { | |
var searchText string | |
callApi := func() { | |
fmt.Printf("Called API with search string %s\n", searchText) | |
} | |
onChange := debounce(func() { | |
callApi() | |
}, "150ms") | |
// Simulate user typing in search bar... | |
searchPhrase := "Apple Computers" | |
for i, c := range searchPhrase { | |
searchText = searchText + string(c) | |
onChange() | |
if i%3 == 1 { | |
time.Sleep(200 * time.Millisecond) | |
} | |
time.Sleep(50 * time.Millisecond) | |
} | |
time.Sleep(200 * time.Millisecond) | |
} | |
// Prints | |
/* | |
Debounce called 1 times | |
Debounce called 2 times | |
Called API with search string Ap | |
Debounce called 3 times | |
Debounce called 4 times | |
Debounce called 5 times | |
Called API with search string Apple | |
Debounce called 6 times | |
Debounce called 7 times | |
Debounce called 8 times | |
Called API with search string Apple Co | |
Debounce called 9 times | |
Debounce called 10 times | |
Debounce called 11 times | |
Called API with search string Apple Compu | |
Debounce called 12 times | |
Debounce called 13 times | |
Debounce called 14 times | |
Called API with search string Apple Computer | |
Debounce called 15 times | |
Called API with search string Apple Computers | |
Program exited. | |
*/ | |
// Try it at https://go.dev/play/p/GCUvOJL3aym |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment