一 大概理解
防抖和节流用于规避频繁触发事件导致大量计算,从而影响页面发生抖动甚至卡顿。 防抖是触发事件单位时间后执行,如果单位时间内再次触发那么时间将会重新结算。 节流是在触发即执行,但在单位时间内触发将不再执行。
防抖Debounce
防抖利用定时器
setTimeOut触发事件单位时间后执行,如果单位时间内再次触发那么时间将会重新结算。
export function Debounce(fn, delay) {
let timer = null;
let self = this;
return (...args) => {
if (timer){
clearTimeout(timer);
}
timer = setTimeout(()=>{
fn.apply(self, ...args);
}, delay)
}
}
节流Throttle
节流利用时间戳来实现 触发即执行,但在单位时间内触发将不再执行。
export function Throttle(fn, delay) {
let last = 0;
let self = this;
return (...args)=>{
if (last == 0 || Date.now() > last) {
fn.apply(self, ...args);
last = Date.now() + delay;
}
}
}
二,怎么使用
例如在vue里面使用
methods:{
handleThrottle: Throttle(function () {
console.log('Throttle'+ Math.random())
},3000),
handleDebounce: Debounce(function () {
console.log('Debounce'+ Math.random())
},3000),
}
应用场景
防抖(debounce)
- search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
- window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
节流(throttle)
-
鼠标不断点击触发,mousedown(单位时间内只触发一次)
-
监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断