Boing (boing v0.1.0)

View Source

A key-based debouncer.

Actions are debounced by specifying a key for related actions. When the first action for that key occurs, a 1 second (by default, but configurable) timer is started. The timer is restarted for each subsequent request to the same key that occurs before the timer expires. When the timer expires, the most recent request is permitted, and the previous requests are debounced.

Implementation details

Internally, this module uses Registry and DynamicSupervisor to start a unique registered :gen_statem for each key with an active timer. Requests make a blocking call to that process, which when the timer expires returns :ok to the most recent request, and {:error, debounced: key} to all others.

Processes are short-lived and de-register themselves once the timer expires.

The keys used are associated with a Registry that is started as part of Boing's supervision tree, and can be considered global. All calls made to Boing.debounce/2 for the same key within the timeout period are made to the same :gen_statem process, which will block and return when the timer expires.

Summary

Functions

Debounce requests for the specified key.

Functions

debounce(key, timeout \\ nil)

@spec debounce(key :: Registry.key(), timeout :: timeout() | nil) ::
  :ok | {:error, [{:debounced, Registry.key()}]}

Debounce requests for the specified key.

timeout is the number of milliseconds to wait before allowing the request. Defaults to 1000ms.

Initially, no timer is active. When this function is called for a key which has no active timer, a new timer is started for timeout milliseconds (1 second by default). Any subsequent calls while the timer is active restart the timer. When the timer expires, :ok is returned to the most recent call, and {:error, debounced: key} to all the other calls that were made while the timer was active.