防抖和節流的做用都是防止函數屢次調用。區別在於,假設一個用戶一直觸發這個函數,且每次觸發函數的間隔小於wait,防抖的狀況下只會調用一次,而節流的 狀況會每隔必定時間(參數wait)調用函數。
節流是將屢次執行變成每隔一段時間執行。 每隔一段時間後執行一次,也就是下降頻率,將高頻操做優化成低頻操做。
mousemove
事件的時候, 如鼠標移動。keyup
事件的狀況, 如搜索。scroll
事件的時候, 譬如鼠標向下滾動中止時觸發加載數據。resize
事件// function resizehandler(fn, delay){ // clearTimeout(fn.timer); // fn.timer = setTimeout(() => { // fn(); // }, delay); // } // window.onresize = () => resizehandler(fn, 1000);
function resizehandler(fn, delay){ let timer = null; return function() { const context = this; const args=arguments; clearTimeout(timer); timer = setTimeout(() => { fn.apply(context,args); }, delay); } } window.onresize = resizehandler(fn, 1000);
一段時間內觸發事件只執行一次。javascript
function resizehandler(fn, delay, duration) { let timer = null; let beginTime = +new Date(); return function() { const context = this; const args = arguments; const currentTime = +new Date(); timer && clearTimeout(timer); if ((currentTime - beginTime) >= duration) { fn.call(context, args); beginTime = currentTime; } else { timer = setTimeout(() => { fn.call(context, args) }, delay); } } } window.onresize = resizehandler(fn, 1000, 1000);
Demo
CodePen-demojava
參考文章
http://www.alloyteam.com/2012...