35 lines
1.2 KiB
Dart
35 lines
1.2 KiB
Dart
import 'dart:async';
|
|
|
|
/// Static map-based debouncer/throttler. Replaces the `easy_debounce` package
|
|
/// with a minimal in-house implementation: each unique [tag] tracks its own
|
|
/// pending Timer and gating flag.
|
|
class Debouncer {
|
|
Debouncer._();
|
|
|
|
static final Map<String, Timer> _debounceTimers = {};
|
|
static final Map<String, Timer> _throttleTimers = {};
|
|
|
|
/// Coalesces calls under [tag]: the [action] runs once [delay] has elapsed
|
|
/// without further calls for the same tag.
|
|
static void debounce(String tag, Duration delay, void Function() action) {
|
|
_debounceTimers[tag]?.cancel();
|
|
_debounceTimers[tag] = Timer(delay, () {
|
|
_debounceTimers.remove(tag);
|
|
action();
|
|
});
|
|
}
|
|
|
|
/// Runs [action] immediately and ignores subsequent calls under the same
|
|
/// [tag] until [duration] has elapsed.
|
|
static void throttle(String tag, Duration duration, void Function() action) {
|
|
if (_throttleTimers.containsKey(tag)) return;
|
|
_throttleTimers[tag] = Timer(duration, () => _throttleTimers.remove(tag));
|
|
action();
|
|
}
|
|
|
|
static void cancel(String tag) {
|
|
_debounceTimers.remove(tag)?.cancel();
|
|
_throttleTimers.remove(tag)?.cancel();
|
|
}
|
|
}
|