throttle static method
节流函数
限制函数执行频率,在指定时间内只执行一次
func 要节流的函数
delay 节流时间
返回节流后的函数和取消函数
示例:
final (throttledFn, cancel) = FuncUtils.throttle(() {
print('执行节流操作');
}, Duration(seconds: 1));
throttledFn(); // 立即执行
throttledFn(); // 被忽略
throttledFn(); // 被忽略
// 1秒后可以再次执行
Implementation
static (void Function(), void Function()) throttle(
void Function() func,
Duration delay,
) {
bool isThrottled = false;
Timer? timer;
void throttledFn() {
if (!isThrottled) {
func();
isThrottled = true;
timer = Timer(delay, () {
isThrottled = false;
timer = null;
});
}
}
void cancel() {
timer?.cancel();
timer = null;
isThrottled = false;
}
return (throttledFn, cancel);
}