throttle method

void throttle([
  1. dynamic callback
])

Implementation

void throttle([callback]) {
  assert(callback != null || this.callback != null);
  Duration elapsed = DateTime.now().difference(lastExec);

  void exec() {
    lastExec = DateTime.now();
    if (callback != null) {
      callback();
    } else {
      this.callback(args);
    }
  }

  if (elapsed.compareTo(delay) >= 0 ||
      (max != null && elapsed.compareTo(max!) >= 0)) {
    exec();
  }

  ///cancel the timeout scheduled for trailing callback
  if (timeoutId != null) timeoutId!.cancel();

  if (noTrailing == false) {
    ///there should be a trailing callback, so schedule one
    ///buggy here, should be 'delay - elasped' but dart async only supports const Duration for delay
    timeoutId = Timer(delay, exec);
  }
}