防抖函數。
將幾次操作合並為一次操作進行。設置一個計時器,規定在延遲時間后觸發函數,但是在延遲時間內如果再次觸發,就會取消之前的計時器。如此,只有最后一次操作能觸發。代碼如下:
function debounce(fn,wait){ let timer=null; return function(){ let args=arguments,that=this; timer&&clearTimeout(timer); timer=setTimeout(function(){fn.apply(that,args)},wait) } }
節流函數。
一定時間內只觸發一次函數。並且開始觸發一次,結束觸發一次。代碼如下:
function throttle(fun, delay){ let timer = null; let startTime = Date.now(); return function(){ let curTime = Date.now(); let remain = delay - (curTime - startTime); let that = this; let args = arguments; clearTimeout(timer); if(remain <= 0){ fun.apply(that,args); startTime = Date.now(); }else{ timer = setTimeout(fun, remain); } } }