前端 防抖与节流函数

devops · May 26, 2020 · 17 hits

函数防抖

1
2
3
4
5
6
7
8
9
10
const debounce = (fn, ms = 0) => {
let timer = null;

return function(...args){
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this,args);
},ms);
}
}

函数节流

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

const throttle = (fn, delay) => {
let last = 0;

return function() {
let now = Date.now();

if(now - last >= delay) {
last = now;
fn.apply(this, arguments);
}
}
}

//升级版,在简易版基础上,如果时间间隔小于delay,则会设置一个新的定时器
//节流+防抖结合体
const throttle = (fn, delay) => {
let last = 0;
let timer = null;

return function() {
let self = this;
let args = arguments;
let now = Date.now();

if(now - last < delay) {
clearTimeout(timer);
timer = setTimeout(()=>{
last = now;
fn.apply(self, args);
},delay)
} else {
last = now;
fn.apply(self, args);
}
}
}

//另一个版本throttle
var throttle = function(fn, interval) {
var timer = null;
var firstTime = true;

return function(){
var self = this;
var args = arguments;

if(firstTime) {
fn.apply(self, args);
return firstTime = false;
}

if(timer) { //如果定时器还在,说明前一次延迟执行还没完成
return false;
}

timer = setTimeout(function(){
clearTimeout(timer);
timer = null;
fn.apply(self, args);
}, interval)
}
}

//30 seconds版本
const throttle = (fn, wait) => {
let inThrottle, timer, last;

return function() {
let self = this;
let args = arguments;
let now = Date.now();

if(!inThrottle) {
fn.apply(self, args);
inThrottle = true;
last = now;
} else {
clearTimeout(timer);
timer = setTimeout(()=>{
if(now - last >= wait) {
fn.apply(self, args);
last = now;
}
}, Math.max(wait - (now - last) ,0))
}
}
}
No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.