lodash源碼學習debounce,throttle


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

直接看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時才會調用,否則一直不會調用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM