防抖主要為了防止事件在短期內(nèi)反復(fù)執(zhí)行。一般有如下兩種方式:
1.自殺模式
2.clearTimeout模式
調(diào)用方法window.onresize = throttle(fn,wait);
function fn(){
console.log('test');
}
wait = 1000;
1.自殺模式
第一次直接運(yùn)行,不存在延時
function throttle(fn,wait) {
var timer;
return function(){
if(!timer) {
timer = setTimeout(function(){
timer = null;
},wait);
fn.apply(this);
}
}
}
2.clearTimeout方式
第一次執(zhí)行存在延時
function throttle(fn,timer) { //防抖函數(shù)
console.log(timeout);
var timeout = null;
return function() { //使用閉包 一個閉包
if (timeout != null) {
console.log(timeout);
clearTimeout(timeout);
}
timeout = setTimeout(fn,timer);
}
}