JavaScript-性能優化,函數節流(throttle)與函數去抖(debounce)

我在寫一個類似百度搜索框的自動提示功能時候,使用了AJAX+keydown事件。調試時候我發現,當在搜索框中輸入文字的時候,控制檯在不停發送AJAX。這在本地服務器測試還好,如果我把它拿到運行環境,很可能出現提示功能卡頓,甚至沒等提示出現用戶就輸入完畢的現象。畢竟大家現在打字都很快啊。於是我找到了一個新技能,函數節流 & 函數去抖。
throttle 和 debounce 是解決請求和響應速度不匹配問題的兩個方案。二者的差異在於選擇不同的策略。

  • throttle 等時間間隔執行函數。
  • debounce 時間間隔 t 內若再次觸發事件,則重新計時,直到停止時間大於或等於 t 才執行函數。

throttle


function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,
      timer;
  return function () {
    var context = scope || this;

    var now = new Date(),
        args = arguments;
    if (last && now - last - threshhold < 0) {
      // hold on to it
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}

調用方法

$('body').on('mousemove', throttle(function (event) {
  console.log('tick');
}, 1000));

debounce

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

調用方法

$('input.username').keypress(debounce(function (event) {
  // do the Ajax request
}, 250));

總結

這兩個方法適用於會重複觸發的一些事件,如:mousemove,keydown,keyup,keypress,scroll等。如果只綁定原生事件,不加以控制,會使得瀏覽器卡頓,用戶體驗差。爲了提高js性能,建議在使用以上及類似事件的時候用函數節流或者函數去抖加以控制。

發佈了82 篇原創文章 · 獲贊 82 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章