lodash源碼學習debounce,throttle

函數去抖(debounce)和函數節流(throttle)一般是用於優化瀏覽器中頻繁觸發的事件,具體內容能夠看這篇文章http://www.cnblogs.com/fsjohnhuang/p/4147810.htmlhtml

直接看lodash中對應方法的實現瀏覽器

_.debounce(func, [wait=0], [options={}])

//debounce.js

var isObject = require('./isObject'),//是不是對象
    now = require('./now'),//獲取當前時間
    toNumber = require('./toNumber');//轉爲爲數字


var FUNC_ERROR_TEXT = 'Expected a function';

var nativeMax = Math.max,//原生最大值方法
    nativeMin = Math.min;//原生最小值方法

/**
 * 函數去抖,也就是說當調用動做n毫秒後,纔會執行該動做,若在這n毫秒內又調用此動做則將從新計算執行時間。
 *
 * @param {Function} func 須要去抖的函數.
 * @param {number} [wait=0] 延遲執行的時間.
 * @param {Object} [options={}] 選項對象.
 * @param {boolean} [options.leading=false] 指定是否在超時前調用.
 * @param {number} [options.maxWait] func延遲調用的最大時間.
 * @param {boolean} [options.trailing=true] 指定是否在超時後調用.
 * @returns {Function} 返回去抖以後的函數.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */
function debounce(func, wait, options) {
  var lastArgs,    //上次調用參數
      lastThis,    //上次調用this
      maxWait,    //最大等待時間
      result,    //返回結果
      timerId,    //timerId
      lastCallTime,    //上次調用debounced時間,即觸發時間,不必定會調用func
      lastInvokeTime = 0, //上次調用func時間,即成功執行時間
      leading = false,    //超時以前
      maxing = false,     //是否傳入最大超時時間
      trailing = true;    //超時以後

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  wait = toNumber(wait) || 0;
  if (isObject(options)) {
    leading = !!options.leading;
    maxing = 'maxWait' in options;
    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function invokeFunc(time) {//調用func,參數爲當前時間
    var args = lastArgs,//調用參數
        thisArg = lastThis;//調用的this

    lastArgs = lastThis = undefined;//清除lastArgs和lastThis
    lastInvokeTime = time;    //上次調用時間爲當前時間
    result = func.apply(thisArg, args);//調用func,並將結果返回
    return result;
  }

  function leadingEdge(time) {//超時以前調用
    lastInvokeTime = time;//設置上次調用時間爲當前時間
    timerId = setTimeout(timerExpired, wait); //開始timer
    return leading ? invokeFunc(time) : result;//若是leading爲true,調用func,不然返回result
  }

  function remainingWait(time) {//設置還須要等待的時間
    var timeSinceLastCall = time - lastCallTime,//距離上次觸發的時間
        timeSinceLastInvoke = time - lastInvokeTime,//距離上次調用func的時間
        result = wait - timeSinceLastCall;//還須要等待的時間

    return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
  }

  function shouldInvoke(time) {//是否應該被調用
    var timeSinceLastCall = time - lastCallTime,//距離上次觸發時間的時間
        timeSinceLastInvoke = time - lastInvokeTime;//距離上次調用func的時間

   
    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  }

  function timerExpired() {//刷新timer
    var time = now();
    if (shouldInvoke(time)) {//若是能夠調用,調用trailingEdge
      return trailingEdge(time);
    }
    timerId = setTimeout(timerExpired, remainingWait(time));//不調用則重置timerId
  }

  function trailingEdge(time) {//超時以後調用
    timerId = undefined;

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (trailing && lastArgs) {//若是設置trailing爲true,而且有lastArgs,調用func
      return invokeFunc(time);
    }
    lastArgs = lastThis = undefined;//清除lastArgs和lastThis
    return result;//不然返回result
  }

  function cancel() {//取消執行
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }

  function flush() {//直接執行
    return timerId === undefined ? result : trailingEdge(now());
  }

  function debounced() {
    var time = now(),
        isInvoking = shouldInvoke(time);//判斷是否能夠調用

    lastArgs = arguments;//獲得參數
    lastThis = this;//獲得this對象
    lastCallTime = time;//觸發時間

    if (isInvoking) {
      if (timerId === undefined) {//首次觸發,調用leadingEdge
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        // 處理屢次頻繁的調用
        timerId = setTimeout(timerExpired, wait);//設置定時器
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {//若是沒有timer,設置定時器
      timerId = setTimeout(timerExpired, wait);
    }
    return result;//返回result
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

module.exports = debounce;

_.throttle(func, [wait=0], [options={}])

//throttle.js

var debounce = require('./debounce'),//debounce方法
    isObject = require('./isObject');//判斷是否爲對象

var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * 函數節流
 *
 * @param {Function} func 須要處理的函數.
 * @param {number} [wait=0] 執行間隔.
 * @param {Object} [options={}] 選項對象.
 * @param {boolean} [options.leading=false] 指定是否在超時前調用.
 * @param {number} [options.maxWait] func延遲調用的最大時間.
 * @param {boolean} [options.trailing=true] 指定是否在超時後調用.
 * @returns {Function} 返回節流以後的函數.
 * @example
 *
 * // Avoid excessively updating the position while scrolling.
 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 *
 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
 * jQuery(element).on('click', throttled);
 *
 * // Cancel the trailing throttled invocation.
 * jQuery(window).on('popstate', throttled.cancel);
 */
function throttle(func, wait, options) {
  var leading = true,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  if (isObject(options)) {
    leading = 'leading' in options ? !!options.leading : leading;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }
  return debounce(func, wait, {
    'leading': leading,
    'maxWait': wait,
    'trailing': trailing
  });
}

module.exports = throttle;

能夠看到這兩個方法基本上都差很少,區別在於throttle初始的時候設置了leading爲true和maxWait,這樣和debounce的區別在於,在第一次觸發的時候throttle會直接調用,而且每隔wait的時間都會調用一次,而debounce第一次不會調用,而且只有當觸發的間隔時間大於wait時纔會調用,不然一直不會調用。app

相關文章
相關標籤/搜索