转自函数防抖和节流 - 简书 (jianshu.com)
https://www.jianshu.com/p/c8b86b09daf0
1.什么情况下使用。
当我们不要频繁调用接口时,或者不想允许用户频繁触发。而我们开发时经常要绑定一些持续触发的事件。如 resize、scroll、mousemove 等等。
下面举例举mousemove事件。
<div id="content"></div>
<script>
let num = 1;
let content = document.getElementById('content');
function count() {
content.innerHTML = num++;
};
content.onmousemove = count;
</script>
上述代码中,div 元素绑定了 mousemove 事件,当鼠标在 div区域中移动的时候会持续地去触发该事件导致频繁执行函数。然后快速增大num的值。如下

所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
防抖函数分为非立即执行版和立即执行版。
非立即执行版:
function debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout); //这里的意思是再次触发时会重新来过
timeout = setTimeout(() => { //等待wait时间后执行func
func.apply(context, args)
}, wait);
}
}
现在优化后代码可以这么用
content.onmousemove = debounce(count,1000);
这里的参数count是把上面的count函数作为参数传参。是我们想要执行的事,比如可以调用接口所在的方法。
防抖函数的代码使用这两行代码来获取 this 和 参数,是为了让 debounce 函数最终返回的函数 this 指向不变以及依旧能接受到 e 参数。
let context = this;
let args = arguments;
立即执行版:
function debounce(func,wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout); //一调用debounce把timeout清掉
let callNow = !timeout; //把calNow变成true
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args) //一调用debounce把timeout清掉,使用这里不用等
待wait秒就能调用func
}
}
立即执行版的意思是触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。
使用方法同上,效果如下

什么是节流
所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数
举例。例如搜索框搜索音乐,下面有多项匹配结果,这个匹配结果可能就是调用后台接口得到的数据,但是用户搜索时会频繁触发调用接口,这时我们想每隔一段时间,比如1s才调用一次。
1319

被折叠的 条评论
为什么被折叠?



