防抖节流
Galloping_Leo 2021-04-14 JavaScript
# 防抖
函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。如下图,持续触发scroll事件时,并不执行handle函数,当1000毫秒内没有触发scroll事件时,才会延时触发scroll事件。

防止在持续触发事件时回调函数过多的执行,如输入框索。

let input = `<input type="text" id="my-input"/>`;
document.body.innerHTML = input;
let Myinput = document.getElementById("my-input");
let debounce = function(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(fn.bind(this, ...args), delay);
};
};
let cb = function() {
console.log("oninput");
};
let newCb = debounce(cb, 500);
Myinput.addEventListener("input", newCb);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 节流
函数节流(throttle):节流通俗解释就比如我们水龙头放水,阀门一打开,水哗哗的往下流,秉着勤俭节约的优良传统美德,我们要把水龙头关小点,最好是如我们心意按照一定规律在某个时间间隔内一滴一滴的往下滴。如下图,持续触发scroll事件时,并不立即执行handle函数,每隔1000毫秒才会执行一次handle函数。

应用场景防止在短时间内快速重复某一操作,如快速点击按钮等。
函数节流主要有两种实现方法:时间戳和定时器。接下来分别用两种方法实现throttle~

function render(...args) {
let r = Math.random() * 255;
let g = Math.random() * 255;
let b = Math.random() * 255;
document.body.style.background = `rgb(${r},${g},${b})`;
}
render();
let callback = function() {
render();
};
// 节流方式 一
let throttle1 = function(fn, delay) {
let timer;
return function(...args) {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.call(this, args);
clearInterval(timer);
timer = undefined;
}, delay);
};
};
// 节流方式 二
let throttle2 = function(fn, delay) {
let pre = 0;
return function(...args) {
let now = new Date();
if (now - pre < delay) {
return;
}
fn.call(this, args);
pre = now;
};
};
let newCallback1 = throttle1(render, 100);
let newCallback2 = throttle2(render, 100);
window.addEventListener("resize", newCallback1);
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
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
# 总结
函数防抖
将几次操作合并为一此操作进行。原理是维护一个计时器,规定在delay时间后触发函数,但是在delay时间内再次触发的话,就会取消之前的计时器而重新设置。这样一来,只有最后一次操作能被触发。
函数节流
使得一定时间内只触发一次函数。原理是通过判断是否到达一定时间来触发函数。
区别
函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。 比如在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。