debounce<T> function

DebouncedFunction<T> debounce<T>(
  1. UnaryFunction<T> delegate,
  2. Duration delay
)

Returns a wrapper function that, when called with x, executes delegate(x) delay from now iff there is no other call to the wrapper between now and delay from now.

The debounced function returns a future that completes when the debounced function is called. The future is completed with the return results of the delegate function.

Implementation

DebouncedFunction<T> debounce<T>(UnaryFunction<T> delegate, Duration delay) {
  Timer? timer;
  Completer? completer;

  return (argument) {
    timer?.cancel();
    completer ??= Completer();
    timer = Timer(delay, () {
      completer!.complete(delegate(argument));
      completer = null;
      timer = null;
    });
    return completer!.future;
  };
}