防抖和節(jié)流
函數(shù)防抖,debounce,基本思路就是把多個(gè)信號合并為一個(gè)信號,也就是在一定時(shí)間內(nèi),某方法不再被觸發(fā)了,就執(zhí)行該方法。
函數(shù)節(jié)流,throttle,基本思路就是讓用戶的方法在某個(gè)時(shí)間段內(nèi)只執(zhí)行一次。
兩者間的核心區(qū)別就在于持續(xù)觸發(fā)事件時(shí),前者合并事件并在最后時(shí)間去觸發(fā)事件,而后者則是隔間時(shí)間觸發(fā)一次~
debounce 防抖
function debounce(fn,delay){
var timeout;
return function(){
clearTimeout(timeout);
var context = this,
arg = arguments,
timeout = setTimeout(function(){
fn.apply(context,args);
},delay);
}
}
throttle 節(jié)流
function throttle(fn,threshhold){
var timeout;
var start = new Date();
var threshhold = threshhold || 160;
return function(){
var context = this,
args = arguments,
curr = new Date()-0;
clearTimeout(timeout);// 總是干掉事件回調(diào)
if(curr-start >= threshhold){
fn.apply(context,args); //方法在某段時(shí)間內(nèi)只執(zhí)行一次
start = curr;
}
else{
//讓方法脫離事件后也能執(zhí)行一次
timeout = setTimeout(function(){
fn.apply(context,args);
},threshhold)
}
}
}