SmartDebouncer class

A smart debouncer that dynamically adjusts its delay based on the user's actual typing speed using the Exponential Moving Average (EMA) algorithm.

Unlike a traditional debouncer with a fixed delay, SmartDebouncer continuously learns the user's typing rhythm and adapts accordingly:

  • Fast typers get a shorter debounce delay for snappy responsiveness.
  • Slow typers get a longer delay to avoid premature API calls.

Algorithm

  1. EMA Update: On each keystroke, the interval between keystrokes is smoothed via EMA:

    currentEma = (interval * alpha) + (currentEma * (1 - alpha))
    
  2. Dynamic Delay: The actual debounce delay is calculated as:

    dynamicDelay = currentEma * multiplier
    
  3. Safety Clamp: The delay is clamped between minDelay and maxDelay.

  4. Pause Filtering: If the interval exceeds pauseThreshold, it's treated as a natural pause (not typing), and the EMA is not updated.

Usage

final debouncer = SmartDebouncer();

TextField(
  onChanged: (value) {
    debouncer.run(() {
      // Call your search API here
      searchApi(value);
    });
  },
);

// Don't forget to dispose!
@override
void dispose() {
  debouncer.dispose();
  super.dispose();
}

Constructors

SmartDebouncer({int minDelay = 150, int maxDelay = 800, double alpha = 0.3, int pauseThreshold = 1500, double multiplier = 1.5})
Creates a SmartDebouncer with configurable parameters.

Properties

alpha double
EMA smoothing factor (0.0–1.0).
final
currentDelay int
Returns the current calculated dynamic delay in milliseconds, clamped between minDelay and maxDelay.
no setter
currentEma double
Returns the current EMA value (for debugging/testing purposes).
no setter
hashCode int
The hash code for this object.
no setterinherited
maxDelay int
Maximum debounce delay in milliseconds.
final
minDelay int
Minimum debounce delay in milliseconds.
final
multiplier double
Multiplier applied to the EMA to compute the debounce delay.
final
pauseThreshold int
Threshold in milliseconds to detect natural pauses.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

dispose() → void
Cancels the current timer to prevent memory leaks.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
reset() → void
Resets the EMA back to its initial value and clears the last call time.
run(void action()) → void
Executes action after a dynamically calculated debounce delay.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited