js 函數節流和防抖

js 函數節流和防抖

throttle 節流

事件觸發到結束後只執行一次。

應用場景

  • 觸發mousemove事件的時候, 如鼠標移動。
  • 觸發keyup事件的情況, 如搜索。
  • 觸發scroll事件的時候, 譬如鼠標向下滾動停止時觸發加載數據。

coding

方法1 防抖
// function resizehandler(fn, delay){
//   clearTimeout(fn.timer);
//   fn.timer = setTimeout(() => {
//      fn();
//   }, delay);
// }
// window.onresize = () => resizehandler(fn, 1000);
方法2 閉包 防抖
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);

debounce 防抖

事件出發後一定的事件內執行一次。

應用場景

  • window 變化觸發resize事件是, 只執行一次。
  • 電話號碼輸入的驗證, 只需停止輸入後進行一次。

coding

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-demo

參考文章
http://www.alloyteam.com/2012...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章