debounce & throttle
那该多好 Lv2

防抖、节流

函数防抖

n秒内只要触发事件,就重新计时,
一直触发事件处理函数的程序永远不能被执行

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
/**
* fn 需要设置防抖的函数
* time 执行时需要延迟的时间
* triggleNow 是否马上触发第一次
**/
function test() {
console.log(1);
}
box.onmouseover = debounce(test, 1000, false);
function debounce(fn, time, triggleNow) {
var t = null;
var debounced = function () {
var _self = this,
args = arguments;
if (t) {
clearTimeout(t)
}
if (triggleNow) {
var exec = !t;
t = setTimeout(() => {
t = null
}, time)
if (exec) {
fn.apply(_self, args)
}
} else {
t = setTimeout(() => {
fn.apply(_self, args)
}, time)
}
}
debounced.remove = function () {
clearTimeout(t);
t = null;
}
return debounced
}

函数节流

事件被触发,n秒之内只执行一次事件处理函数

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
var input = document.getElementById('input');

input.onkeyup = throttle(check, 1000);

function check() {
var val = this.value;
if (val.length < 6) {
console.log('Invalid length');
} else {
console.log('success');
}
}

function throttle(fn, delay){
var t = null,
begin = new Date().getTime();
return function(){
var _self = this,
args = argumens,
cur = new Date().getTime();
clearTimeout(t);
if( cur - begin >= delay ){
fn.apply(_self, args);
begin = cur;
}else{
t = setTimeout( ()=>{
fn.apply(_self, args)
},delay)
}
}
}
 评论