Skip to content

Latest commit

 

History

History
96 lines (77 loc) · 4.25 KB

README.md

File metadata and controls

96 lines (77 loc) · 4.25 KB

debounce

Go package that provides a number of debounce patterns as a set of easy to use functions.

Go Reference GitHub tag (latest SemVer) Actions Status Coverage GitHub issues GitHub pull requests License Status

Provides functions to debounce function calls, i.e., to ensure that a function is only executed after a certain amount of time has passed since the last call.

Debouncing can be useful in scenarios where function calls may be triggered rapidly, such as in response to user input, but the underlying operation is expensive and only needs to be performed once per batch of calls.

This package provides several debouncing functions, each with different characteristics:

  • New: creates a new debounced function that will wait a fixed duration before calling the original function, regardless of how many times the debounced function is called in the meantime.
  • NewMutable: creates a new debounced function that will wait a fixed duration before calling the last function that was passed to the debounced function, regardless of how many times the debounced function is called in the meantime. This allows the function to be changed dynamically.
  • NewWithMaxWait: creates a new debounced function that will wait a fixed duration before calling the original function, but will also enforce a maximum wait time, after which the function will be called regardless of whether new calls have been made. This ensures that the function is not delayed indefinitely if calls keep coming in.
  • NewMutableWithMaxWait: creates a new debounced function that combines the characteristics of NewMutable and NewWithMaxWait, i.e., it will wait a fixed duration before calling the last function that was passed to the debounced function, but will also enforce a maximum wait time. All debouncing functions are safe for concurrent use in goroutines and can be called multiple times.

Import

import "github.com/romdo/go-debounce"

Usage

func main() {
	// Create a new debouncer that will wait 100 milliseconds since the last
	// call before calling the callback function.
	debounced, _ := debounce.New(100*time.Millisecond, func() {
		fmt.Println("Hello, world!")
	})

	debounced()
	time.Sleep(75 * time.Millisecond) // +75ms = 75ms
	debounced()
	time.Sleep(75 * time.Millisecond) // +75ms = 150ms
	debounced()
	time.Sleep(150 * time.Millisecond) // +150ms = 300ms, wait expired at 250ms

	// Output:
	// Hello, world!
}

Documentation

Please see the Go Reference.

Contributing

Contributions to this package are welcome! Please open an issue or a pull request on GitHub.

License

MIT