throttle static method

void throttle(
  1. Function callback, {
  2. String? key,
  3. Duration duration = const Duration(milliseconds: 300),
})

Implementation

static void throttle(
  Function callback, {
  String? key,
  Duration duration = const Duration(milliseconds: 300),
}) {
  // key 优先使用外部传入的稳定标识;否则退化为 callback 实例(仅当 callback 实例稳定时才有效)
  final effectiveKey = (key ?? identityHashCode(callback).toString());
  final throttleKey = effectiveKey.hashCode ^ duration.inMilliseconds;
  final now = DateTime.now();
  final lastTime = _throttleTimes[throttleKey];

  if (lastTime == null || now.difference(lastTime) > duration) {
    callback();
    _throttleTimes[throttleKey] = now;
  }
}