-
Notifications
You must be signed in to change notification settings - Fork 0
/
debounce_throttle.js
71 lines (64 loc) · 1.87 KB
/
debounce_throttle.js
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
// 1. 防抖函数`debounce`的功能就相当于帮你判断什么时候该按下快门
// 2. `fn`相当于快门
// 3. `threshhold`(阈值)就相当于`threshhold`间隔内没有再次抖动才表示稳定了
// 4. 只有稳定之后才会按下快门即执行fn
function debounce(fn, threshhold){
if(!fn instanceof Function) {
throw new TypeError('Expected a function')
}
let timer = null;
return function (...arg) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arg)
},threshhold)
};
}
function throttle2(fun, threshhold) {
if(!fun instanceof Function) {
throw new TypeError('Expected a function')
}
let limited = false; // 节流阀标志位
let timer = null;
let start = Date.now();
threshhold = threshhold || 500
return function (...args) {
let current = Date.now();
limited = limited && current- start < threshhold
if (limited) {
clearTimeout(timer)
timer = setTimeout(() => {
limited = true
start = Date.now()
fun.apply(this, args)
}, threshhold)
}else {
limited = true
start = Date.now();
fun.apply(this,args)
}
}
}
// 间隔时间threshhold内值执行一次
function throttle(fn, threshhold) {
if(!fn instanceof Function) {
throw new TypeError('Expected a function')
}
let limited = false; // 节流阀标志位
let start = Date.now();
threshhold = threshhold || 500
return function (...args) {
let current = Date.now();
limited = limited && current- start < threshhold
if(!limited) {
fn.apply(this,args);
limited = true;
start = Date.now();
}
}
}
export {
debounce,
throttle,
throttle2
}