鼠标移动事件onmousemove, 滚动滚动条事件onscroll等瞬间的操作都会导致这些事件会被高频触发。 如果事件的回调函数较为复杂,可能会导致响应跟不上触发,出现页面卡顿,假死现象
防抖: 当持续触发事件时,每一次都要清空定时器,重新开始。
eg:实时搜索
实现1:
var timer = null;
function debounce (){
clearTimeout(timer);
timer = setTimeout(function(){
console.log("函数防抖");
}, 300);
};
实现2:
function debunce(handler,delay){
var timer = null;
return function(){
var _self = this,args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
handler.apply(_self,args);
},delay);
}
节流:当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
eg:窗口调整(调整大小),页面滚动(滚动),抢购时疯狂点击(鼠标按下)
实现1:
var timer = null;
function throttle(){
if(!timer){
timer = setTimeout(function(){
console.log("函数节流");
timer = null;
}, 300);
}
};
实现2:
function throttle(handler, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
handler.apply(context, args);
timer = null;
}, delay);
}
}
}