Skip to content

Instantly share code, notes, and snippets.

@AlexV525
Created December 26, 2020 06:33
Show Gist options
  • Save AlexV525/3340dec07caeda5b65540beac71d90bf to your computer and use it in GitHub Desktop.
Save AlexV525/3340dec07caeda5b65540beac71d90bf to your computer and use it in GitHub Desktop.
De-bounce and throttle
///
/// [Author] Alex (https://github.com/AlexV525)
/// [Date] 2020-12-26 11:51
///
import 'dart:async';
import 'package:flutter/foundation.dart';
/// 防抖和节流
///
/// 需要注意的是,在方法里进行 [setState] 后,防抖节流都会失效,函数会重新生成新实例。
extension DebounceThrottlingExtension on Function {
/// 防抖 (debounce)
VoidCallback debounce([Duration duration = const Duration(seconds: 1)]) {
assert(duration != null && duration > Duration.zero);
Timer _debounce;
return () {
// 还在时间之内,抛弃上一次
// 执行最后一次
if (_debounce?.isActive ?? false) {
_debounce.cancel();
}
_debounce = Timer(duration, () {
this.call();
});
};
}
/// 节流 (throttle)
VoidCallback throttle([Duration duration = const Duration(seconds: 1)]) {
assert(duration != null && duration > Duration.zero);
Timer _throttle;
return () {
print(_throttle);
// 执行第一次
if (_throttle?.isActive ?? false) {
return;
}
this.call();
_throttle = Timer(duration, () {});
};
}
}
/// 而下面的两个方法没有这种顾虑。
/// 防抖
VoidCallback debounce(
VoidCallback callback, [
Duration duration = const Duration(seconds: 1),
]) {
assert(callback != null);
assert(duration != null && duration > Duration.zero);
Timer _debounce;
return () {
// 还在时间之内,抛弃上一次
// 执行最后一次
if (_debounce?.isActive ?? false) {
_debounce.cancel();
}
_debounce = Timer(duration, () {
callback.call();
});
};
}
/// 节流
VoidCallback throttle(
VoidCallback callback, [
Duration duration = const Duration(seconds: 1),
]) {
assert(callback != null);
assert(duration != null && duration > Duration.zero);
Timer _throttle;
return () {
// 执行第一次
if (_throttle?.isActive ?? false) {
return;
}
callback.call();
_throttle = Timer(duration, () {});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment