对于某些高频事件:input 输入框的change事件,window.resize , 滚动条等
什么是防抖:
对于短时间内连续触发的事件(上面的滚动事件),防抖的含义就是让某个时间期限(如上面的1000毫秒)内,事件处理函数只执行一次。
什么是节流:
如果短时间内大量触发同一事件,那么在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效。
区别:
如果短时间内大量触发同一事件,只会执行一次函数(一般只在意结果)。
节流是某段时间间隔内只执行一次函数(连续触发,但是执行间隔自定义)
防抖函数:
var debounce=function(fn, wait){
var timer = null;
return function(){
if(timer!== null) clearTimeout(timeout);
timer= setTimeout(fn, wait);
}
};
function yourfunc(){
console.log(Math.random())
};
window.addEventListener('scroll',debounce(yourfunc,1000));
节流函数:
var throttle = function(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
}
}
function yourfunc() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(yourfunc, 1000));