Last active
March 13, 2024 10:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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