debounce function for golang

for my presentation tool slide-serve i used fsnotify to watch for changes to reload the browser. But for whatever reason, the events always came in doubled… so i tried to port the idea behind the underscore or RX debounce function to golang. This is the solution i came up with:

func debounce(interval time.Duration, input chan string, cb func(arg string)) {
	var item string
	timer := time.NewTimer(interval)
	for {
		select {
		case item = <-input:
			timer.Reset(interval)
		case <-timer.C:
			if item != "" {
				cb(item)
			}
		}
	}
}

usage

in this example, the debounce time is one second, the input eventChanel is created to send events to debounce. The actual processing happens in the callback function.

eventChan := make(chan string)
go debounce(time.Second, eventChan, func(name string) {
  // this function is only called once - with the last event
})

// ...

eventChan <- "send"
eventChan <- "a lot of"
eventChan <- "events"

dont’t forget to start as a go-routine, otherwise you are stuck in the for loop ;)

Last posts

Tags