throttle static method

void Function() throttle(
  1. Function fun,
  2. int wait, {
  3. Object? key,
  4. bool trailing = false,
})

对目标函数进行包装,返回一个节流函数,会忽略指定时间内的多次执行

  • wait 节流时间(毫秒)
  • key 指定函数标识符
  • trailing 当多次调用函数时,确保最后一次函数执行

Implementation

static void Function() throttle(
  Function fun,
  int wait, {
  Object? key,
  bool trailing = false,
}) {
  assert(wait > 0);

  // 默认 key 就是函数自身的哈希码,每次执行时若哈希码不同,那么节流就会失效,
  // 当 fun 是一个匿名函数、同时 throttle 被重建,那么节流一定会失效,例如:
  // void demo() {
  //   DartUtil.throttle(() => print('hello'), 1000)();
  // }
  key ??= fun.hashCode;

  return () {
    if (_throttleKeys.contains(key)) {
      // 确保最后一次函数执行
      if (trailing) {
        _throttleTrailingKeys[key]?.cancel();
        _throttleTrailingKeys[key!] = setTimeout(() {
          _throttleTrailingKeys.remove(key);
          fun();
        }, wait);
      }

      return;
    } else {
      if (trailing) _throttleTrailingKeys[key]?.cancel();

      _throttleKeys.add(key!);
      setTimeout(() {
        _throttleKeys.remove(key);
      }, wait);

      fun();
    }
  };
}