1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import 'dart:async';
- Map<String, Timer> _funcThrottle = {};
- Map<String, DateTime> _funcThrottleLastCall = {};
- Function? _lastFunc;
- Function throttle(Function func, String funcTag, [int milliseconds = 2000]) {
- target() {
-
- String key = funcTag.toString();
- Timer? _timer = _funcThrottle[key];
- if (_timer == null) {
-
- if (_funcThrottleLastCall[key] == null) {
- func.call();
- _funcThrottleLastCall[key] = DateTime.now();
- } else {
-
- if (DateTime.now()
- .difference(_funcThrottleLastCall[key]!)
- .inMilliseconds >
- milliseconds) {
- _funcThrottleLastCall[key] = DateTime.now();
- func.call();
- } else {
- _lastFunc = func;
- }
- }
- _timer = Timer(Duration(milliseconds: milliseconds), () {
- final lastFunc = _lastFunc;
- if (lastFunc != null) {
- _lastFunc!.call();
- _funcThrottleLastCall[key] = DateTime.now();
- _lastFunc = null;
- }
- Timer? t = _funcThrottle.remove(key);
- t?.cancel();
- t = null;
- });
- _funcThrottle[key] = _timer;
- } else {
- _lastFunc = func;
- }
- }
- target();
- return target;
- }
|