不定期更新的源码阅读日常——lodash-3

  今天我们来读lodash的节流防抖部分代码。  节流和防抖,是限制函数高频执行的一种手段。它们概念的区别在于,防抖合并多次函数执行为一次;节流是在一定的时间内函数只执行一次。具体的区别可以参考lodash官网推荐的这篇文章。  虽然明细了概念的区别,但是在lodash源码中,这两个方式其实是一个实现。lodash中_.debounce对应防抖,_.throttle则对应节流。我们先来看一...
摘要由CSDN通过智能技术生成

  今天我们来读lodash的节流防抖部分代码。

  节流和防抖,是限制函数高频执行的一种手段。它们概念的区别在于,防抖合并多次函数执行为一次;节流是在一定的时间内函数只执行一次。具体的区别可以参考lodash官网推荐的这篇文章

  虽然明细了概念的区别,但是在lodash源码中,这两个方式其实是一个实现。lodash_.debounce对应防抖,_.throttle则对应节流。我们先来看一下throttle部分的代码。

/**
  * @param {Function} func: 要节流的函数。
  * @param {Number} wait 需要节流的毫秒
  * @param {Object} options 选项对象
  * [options.leading=true] (boolean): 指定调用在节流开始前。
  *  [options.trailing=true] (boolean): 指定调用在节流结束后。
  * @returns {Function} Returns the new throttled function.
*/
function throttle(func, wait, options) {
   
  var leading = true,
      trailing = true;
  // 非函数抛错
  if (typeof func != 'function') {
   
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  // options 为对象时,进行 leading 和 trailing 的参数设置
  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
  });
}

  throttle函数非常的简单,进行默认值选项leadingtrailing的设置。然后对入参类型进行检测,接着直接返回调用debounce函数的内容。尽管lodash官方上面画了不少篇幅来介绍节流防抖的感念区别,其实防抖函数就是直接使用节流函数的逻辑来实现的。

  让我们把视线转到debounce函数。debounce的配置设置是一个高阶函数,放入你需要防抖的函数调用配置,返回处理好的函数。先来看一下函数的入参以及入参处理。

/**
  * @param {Function} func The function to debounce.
  * @param {number} [wait=0] The number of milliseconds to delay.
  * @param {Object} [options={}] The options object.
  * @param {boolean} [options.leading=false]
  *  Specify invoking on the leading edge of the timeout.
  * @param {number} [options.maxWait]
  *  The maximum time `func` is allowed to be delayed before it's invoked.
  * @param {boolean} [options.trailing=true]
  *  Specify invoking on the trailing edge of the timeout.
  * @returns {Function} Returns the new debounced function.
*/
function debounce(func, wait
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值