1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import 'dart:async';
- // 节流函数列表
- Map<String, Timer> _funcThrottle = {};
- // 节流函数上次触发的时间
- Map<String, DateTime> _funcThrottleLastCall = {};
- Function? _lastFunc;
- /// 函数节流
- ///
- /// [func]: 要执行的方法
- /// [funcTag]: 方法标识符
- /// [milliseconds]: 要迟延的毫秒时间
- Function throttle(Function func, String funcTag, [int milliseconds = 2000]) {
- target() {
- // print('对 $funcTag 进行函数节流');
- 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;
- }
|