common_utils.dart
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import 'dart:async';
class JhCommonUtils {
static Timer _debounceTimer;
/// 防抖 (传入所要防抖的方法/回调与延迟时间)
static void debounce(Function func, [int delay = 500]) {
if (_debounceTimer != null) {
_debounceTimer?.cancel();
}
_debounceTimer = Timer(Duration(milliseconds: delay), () {
func.call();
_debounceTimer = null;
});
}
/// 防抖 (传入所要防抖的方法/回调与延迟时间)
static debounce2(Function func, [int delay = 500]) {
Timer timer;
return () {
if (timer != null) {
timer?.cancel();
}
timer = Timer(Duration(milliseconds: delay), () {
func.call();
timer = null;
});
};
}
/// 录入框防抖 (传入所要防抖的方法/回调与延迟时间)
static debounceInput(Function(dynamic) func, [int delay = 500]) {
Timer timer;
return (dynamic value) {
if (timer != null) {
timer?.cancel();
}
timer = Timer(Duration(milliseconds: delay), () {
func.call(value);
timer = null;
});
};
}
static Timer _throttleTimer;
static bool _throttleFlag = true;
/// 节流 (传入所要节流的方法/回调与延迟时间)
static void throttle(Function func, [int delay = 500]) {
if (_throttleFlag) {
func.call();
_throttleFlag = false;
return;
}
if (_throttleTimer != null) {
return;
}
_throttleTimer = Timer(Duration(milliseconds: delay), () {
func.call();
_throttleTimer = null;
});
}
/// 节流 (传入所要节流的方法/回调与延迟时间)
static throttle2(Function func, [int delay = 500]) {
Timer timer;
bool firstTime = true;
return () {
if (firstTime) {
func.call();
firstTime = false;
return;
}
if (timer != null) {
return;
}
timer = Timer(Duration(milliseconds: delay), () {
func.call();
timer = null;
});
};
}
/// 节流 (传入所要节流的方法/回调与延迟时间)
static throttle3(Function func, [int delay = 500]) {
Timer timer;
bool isExecuting = false;
return () {
if (isExecuting) return;
isExecuting = true;
timer?.cancel();
timer = Timer(Duration(milliseconds: delay), () {
func.call();
isExecuting = false;
});
};
}
}