1. 程式人生 > 其它 >多執行緒簡單程式設計

多執行緒簡單程式設計

防抖 functiondebounce(fn,delay){ lettimer=null;
returnfunction(){ letcontext=this; letargs=arguments;
if(timer!==null){ clearTimeout(timer); }
timer=setTimeout(function(){ fn.apply(context,args); },delay) } } 節流 functionthrottle(fn,delay){ lettimer=null; letstartTime=Date.now();
returnfunction(){ letnowTime=Date.now(); letcontext=this; letremainning=delay-(nowTime-startTime); letargs=arguments;
clearTimeout(timer) if(remainning<=0){ fn.apply(context,args); startTime=Date.now(); }else{ timer=setTimeout(fn,remainning) } } }
functionhandle(){ console.log('節流函式執行'); }
constthrottleHandle=throttle(handle,1000) throttleHandle() throttleHandle() throttleHandle() throttleHandle() throttleHandle()
//時間戳版--第一次出發肯定立即執行 functionthrottleDate(fn,delay){ letlast=0;
returnfunction(){ letnow=Date.now(); if(now-last>=delay){ fn.apply(this,arguments) last=Date.now() } } }
//定時器版--最後一次觸發,delay時間後才執行 functionthrottleTimeout(fn,delay){ lettimer=null;
returnfunction(){ letcontext=this; letargs=arguments;
if(!timer){ timer=setTimeout(function(){ fn.apply(context,args) clearTimeout(timer) },delay)
}
} }