关于防抖和节流

防抖 debounce

在事件被触发n秒后再执行回调函数,如果在这n秒内又被触发,则重新计时。

防抖 类似于游戏里的 施法前摇 ,只有当前摇吟唱事件结束时,才能触发技能。

实际场景:在输入框里输入一段文字,不断触发某事件,如向后台一直发送数据,故需要防抖来控制此时不断执行的回调函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let input = document.querySelector("input");

let timer;
function debounce(fn, delay = 300) {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(fn, delay);
};
}

input.onkeydown = debounce(() => console.log(input.value), 1000);

利用闭包封装一个 debounce 函数,从而达到1s内在 input 框反复按键里不会触发事件,若停下按键操作1s后触发事件。

节流 throttling

每隔一段时间,只执行一次函数。

节流 类似于游戏里的 技能CD ,一段时间只执行一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let div = document.querySelector("div");

function throttling(fn, delay = 1000) {
let timer;
return function () {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this,arguments)
timer = null;
}, delay);
};
}

div.ondrag = throttling((e) => console.log(e.offsetX));

利用闭包封装一个 throttling 函数,从而达到拖拽 div 时每1s触发一次事件。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!