throttle.dart 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'dart:async';
  2. // 节流函数列表
  3. Map<String, Timer> _funcThrottle = {};
  4. // 节流函数上次触发的时间
  5. Map<String, DateTime> _funcThrottleLastCall = {};
  6. Function? _lastFunc;
  7. /// 函数节流
  8. ///
  9. /// [func]: 要执行的方法
  10. /// [funcTag]: 方法标识符
  11. /// [milliseconds]: 要迟延的毫秒时间
  12. Function throttle(Function func, String funcTag, [int milliseconds = 2000]) {
  13. target() {
  14. // print('对 $funcTag 进行函数节流');
  15. String key = funcTag.toString();
  16. Timer? _timer = _funcThrottle[key];
  17. if (_timer == null) {
  18. // 判断是否是第一次调用
  19. if (_funcThrottleLastCall[key] == null) {
  20. func.call();
  21. _funcThrottleLastCall[key] = DateTime.now();
  22. } else {
  23. // 判断是否超过了延迟时间
  24. if (DateTime.now()
  25. .difference(_funcThrottleLastCall[key]!)
  26. .inMilliseconds >
  27. milliseconds) {
  28. _funcThrottleLastCall[key] = DateTime.now();
  29. func.call();
  30. } else {
  31. _lastFunc = func;
  32. }
  33. }
  34. _timer = Timer(Duration(milliseconds: milliseconds), () {
  35. final lastFunc = _lastFunc;
  36. if (lastFunc != null) {
  37. _lastFunc!.call();
  38. _funcThrottleLastCall[key] = DateTime.now();
  39. _lastFunc = null;
  40. }
  41. Timer? t = _funcThrottle.remove(key);
  42. t?.cancel();
  43. t = null;
  44. });
  45. _funcThrottle[key] = _timer;
  46. } else {
  47. _lastFunc = func;
  48. }
  49. }
  50. target();
  51. return target;
  52. }