防抖和节流都是用来处理某个事件短时间内过于频繁触发的场景,可以减少一个函数无用的触发次数,对性能做出一些优化。
一、防抖函数 debounce
防抖指的是在短时间内大量触发同一事件,只会执行一次函数。也就是说,设置一个计时器,约定delay时间后再触发事件处理,而且每次触发事件都会重新计时,直到delay时间后没有第二次触发操作。防抖的重点在于延迟执行,以最后一次事件触发为准。
源码实现:
function debounce(fn, delay) {
const thisValue = this; //储存this指向
const timer = null; //1.事件触发,先timer清空
return function() { //返回一个新的防抖函数
const args = arguments;
if(timer)
clearTimeout(timer); //2.对于返回的新防抖函数,先清空
timer = setTimeout(() => { //setTimeout函数到延迟时间后会执行函数
fn.call(thisValue, args); //3.然后再执行延迟函数
}, delay);
};
}
应用场景:
- 搜索框/滚动条的监听事件处理
- 连续触发keydown事件
二、节流函数 throttle
节流指的是每隔一段时间就执行一次函数。也就是说,设置一个定时器,约定delay时间后在触发事件处理,如果时间到了,那么执行函数并且重新计时。节流的重点在于间隔执行,以这段时间内的第一次事件触发为准。
源码实现:
function throttle(fn, delay) {
const thisValue = this;
const timer = null;
return function() {
const args = arguments;
if(!timer){ //与防抖的不同
timer = setTimeout(() => { //先到达延迟时间后,再清空并执行延迟函数
timer = null;
fn.call(thisValue, args);
}, delay);
}
}
}
应用场景:
- 鼠标移动,mousemove 事件
- DOM 元素动态定位
- window对象的resize和scroll(无限滚动) 事件
参考资料: