防抖和节流

在前端开发的过程中,我们经常会需要绑定一些持续触发的事件,如 resize、scroll、mousemove 等等,但有些时候我们并不希望在事件持续触发的过程中那么频繁地去执行函数。

通常这种情况下我们怎么去解决的呢?一般来讲,防抖和节流是比较好的解决方案。
用一句比较剪短的话形容两者的区别:
防抖是控制次数,节流是控制频率

防抖

  • 非立即执行版:
    触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
1
2
3
4
5
6
7
8
9
10
11
function debounce(func, wait) {
let timeout;
return function () {
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
// 直接用箭头函数就可以解决this指向
func.apply(this, args)
}, wait);
}
}
  • 立即执行版:
    立即执行版的意思是触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。
1
2
3
4
5
6
7
8
9
10
11
12
13
function debounce(func,wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
}

节流

1
2
3
4
5
6
7
8
9
10
11
12
function throttle(func, wait) {
let timeout;
return function() {
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(this, args)
}, wait)
}
}
}