Skip to content

Instantly share code, notes, and snippets.

@dipendra-sharma
Last active March 13, 2024 10:14
Show Gist options
  • Save dipendra-sharma/3a66f57229aa67a0c27b1397b71a135a to your computer and use it in GitHub Desktop.
Save dipendra-sharma/3a66f57229aa67a0c27b1397b71a135a to your computer and use it in GitHub Desktop.
This gist demonstrates how to implement debounce functionality in Dart using the `dart:async` library. Debounce is a technique used to delay the execution of an action until a certain amount of time has passed without any further invocations.
import 'dart:async';
class Debouncer {
final Duration delay;
Timer? _timer;
Debouncer({required this.delay});
Future<T> run<T>(Future<T> Function() action) async {
if (_timer != null) {
_timer!.cancel();
}
final completer = Completer<T>();
_timer = Timer(delay, () async {
T result = await action();
completer.complete(result);
});
return completer.future;
}
}
class Throttler {
final Duration duration;
DateTime? _lastExecutionTime;
Throttler({required this.duration});
Future<T> run<T>(Future<T> Function() action) async {
final currentTime = DateTime.now();
if (_lastExecutionTime == null ||
currentTime.difference(_lastExecutionTime!) >= duration) {
_lastExecutionTime = currentTime;
return await action();
}
return Future.value(null) as Future<T>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment