throttle static method

Function throttle(
  1. Function func, [
  2. Duration delay = const Duration(milliseconds: 200)
])

节流函数封装 func: 要执行的函数 delay: 节流时间(毫秒)

Implementation

static Function throttle(
  Function func, [
  Duration delay = const Duration(milliseconds: 200),
]) {
  DateTime? lastTime;
  Timer? timer;
  return () {
    final now = DateTime.now();
    if (lastTime == null || now.difference(lastTime!) > delay) {
      lastTime = now;
      func.call();
    } else {
      timer?.cancel();
      timer = Timer(delay - now.difference(lastTime!), () {
        func.call();
        lastTime = DateTime.now();
      });
    }
  };
}