浏览器的防抖和节流

防抖

一个比较形象的比喻就是电梯每进来一个人就要等10秒再运行。

防抖函数代码:

1
2
3
4
5
6
7
8
9
10
11
function debounce(fn, delay) {
let timer = null;
return function () {
let context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}

比较常见的应用是 input 输入框添加防抖

节流

一个比较形象的比喻就是打穿越火线(cf)时,就算一直按着鼠标,也只能在规定射速内射出子弹。

节流代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function throttle(fn, threshhold = 250, scope) {
let last,
deferTimer;
return function () {
let context = scope || this;

let now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}

比较常见的应用是监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断

图片对比

对比

参考

https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function

http://demo.nimius.net/debounce_throttle/

https://remysharp.com/2010/07/21/throttling-function-calls

https://juejin.im/post/5b8de829f265da43623c4261#heading-4