throttle static method

Function throttle(
  1. Function fn, {
  2. int delay = 300,
  3. bool leading = true,
  4. bool trailing = true,
})

函数节流

fn 需要节流的函数 delay 节流延迟时间(毫秒) leading 是否在延迟开始前调用函数 trailing 是否在延迟结束后调用函数

节流函数原理:规定一个时间 delay,在这个时间内,只能触发一次函数。 如果在这个时间内多次触发函数,只有一次生效 适用场景:滚动加载、按钮点击、拖拽等

Implementation

static Function throttle(Function fn, {int delay = 300, bool leading = true, bool trailing = true}) {
  Timer? timer;
  DateTime? previous;
  dynamic result;
  return ([List<dynamic> args = const []]) {
    DateTime now = DateTime.now();
    if (previous == null && leading == false) {
      previous = now;
    }
    int remaining = delay - now.difference(previous ?? now).inMilliseconds;
    if (remaining <= 0 || remaining > delay) {
      if (timer != null) {
        timer!.cancel();
        timer = null;
      }
      previous = now;
      result = Function.apply(fn, args);
    } else if (timer == null && trailing) {
      timer = Timer(Duration(milliseconds: remaining), () {
        previous = leading ? DateTime.now() : null;
        timer = null;
        result = Function.apply(fn, args);
      });
    }
    return result;
  };
}