75 lines
1.7 KiB
Dart
75 lines
1.7 KiB
Dart
import 'dart:async';
|
||
|
||
import 'package:star_lock/app_settings/app_settings.dart';
|
||
|
||
///
|
||
/// 节流器 可以防止一个函数在短时间内被重复调用
|
||
// 创建一个1秒的节流器
|
||
// Throttler throttler = Throttler(Duration(seconds: 1));
|
||
//
|
||
// // 示例函数
|
||
// void myFunction() {
|
||
// print("函数被调用");
|
||
// }
|
||
//
|
||
// // 调用示例函数,会在1秒内只输出一次
|
||
// throttler.throttle(myFunction);
|
||
//
|
||
// // 在自定义时间间隔内防止函数被重复调用
|
||
// Throttler customThrottler = Throttler(Duration(milliseconds: 500)); // 自定义500毫秒的间隔
|
||
// customThrottler.throttle(myFunction); // 在500毫秒内多次调用只会执行一次函数
|
||
//
|
||
// // 在需要时取消节流器
|
||
// customThrottler.cancel(); // 取消节流器,函数再次被调用会立即执行
|
||
|
||
class Throttler {
|
||
Throttler(this._delay);
|
||
|
||
final Duration _delay;
|
||
Timer? _timer;
|
||
late Function _callback;
|
||
|
||
void throttle(Function callback) {
|
||
if (_timer == null || !_timer!.isActive) {
|
||
_callback = callback;
|
||
_timer = Timer(_delay, () {
|
||
_callback();
|
||
_timer?.cancel();
|
||
});
|
||
}
|
||
}
|
||
|
||
void cancel() {
|
||
_timer?.cancel();
|
||
}
|
||
}
|
||
|
||
///
|
||
/// 防止抖动
|
||
///
|
||
class FunctionBlocker {
|
||
FunctionBlocker({required this.duration});
|
||
|
||
bool _blocked = false;
|
||
Duration duration;
|
||
|
||
//阻止函数执行
|
||
void block(Function function) {
|
||
if (!_blocked) {
|
||
_blocked = true;
|
||
function();
|
||
Timer(duration, () {
|
||
_blocked = false;
|
||
});
|
||
}
|
||
}
|
||
|
||
//倒计时禁止
|
||
void countdownProhibited({required Duration duration}) {
|
||
_blocked = true;
|
||
Timer(duration, () {
|
||
_blocked = false;
|
||
});
|
||
}
|
||
}
|