Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Last active November 20, 2022 03:13
Show Gist options
  • Save alexcmgit/77ba9095267c2b339f4693229615e487 to your computer and use it in GitHub Desktop.
Save alexcmgit/77ba9095267c2b339f4693229615e487 to your computer and use it in GitHub Desktop.
import 'dart:async';
void main() {
/// Debounce example
final debounce = debounceIt(Duration(seconds: 2)); // Or DebounceIt(...)
debounce(() => print('First call'));
debounce(() => print('Second call'));
debounce(() => print('Third call'));
debounce(() => print('Fourth call'));
await Future.delayed(Duration(seconds: 2));
/// > 'Fourth call'
}
void main() {
/// Throttle example
final throttle = throttleIt(Duration(seconds: 1)); // Or ThrottleIt(...)
for (var i = 0; i < 500; i++) {
throttle(() => print("Call $i"));
await Future.delayed(Duration(milliseconds: 50));
}
}
void Function(void Function()) debounceIt(Duration duration) {
Timer? debounce;
return (fn) {
debounce?.cancel();
void callback() => ({fn(), debounce?.cancel()});
debounce = Timer(duration, callback);
};
}
class DebounceIt {
final Duration duration;
Timer _debounce;
DebounceIt(this.duration);
void call(void Function() fn) {
_debounce?.cancel();
_debounce = Timer(duration, fn);
}
void dispose() {
_debounce?.cancel();
}
}
void Function(void Function()) throttleIt(Duration duration) {
Timer? throttle;
var allowExec = true;
void resetThrottle(void Function() fn) {
allowExec = false;
void callback() => {allowExec = true, throttle?.cancel()};
throttle = Timer(duration, callback);
fn();
}
return (fn) {
if (!allowExec) return;
resetThrottle(fn);
};
}
class ThrottleIt {
final Duration duration;
Timer _throttle;
var allowExec = true;
ThrottleIt(this.duration);
void _resetThrottle(void Function() fn) {
allowExec = false;
void callback() => {allowExec = true, _throttle?.cancel()};
_throttle = Timer(duration, callback);
fn();
}
void call(void Function() fn) {
if (!allowExec) return;
_resetThrottle(fn);
}
void dispose() {
_throttle?.cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment