debounce<TResult> method

Future<TResult?> debounce<TResult>(
  1. FutureOr<TResult> job(), {
  2. Duration delay = const Duration(milliseconds: 250),
})

Function job is only executed when no other job is scheduled within the delay period.

Implementation

Future<TResult?> debounce<TResult>(FutureOr<TResult> Function() job,
    {Duration delay = const Duration(milliseconds: 250)}) async {
  final key = _scheduledKey = Object();

  await Future.delayed(delay);

  return await runLocked(() async {
    if (_scheduledKey == key) {
      _scheduledKey = null;
      return await job();
    } else {
      return null;
    }
  });
}