lodash源码中debounce函数分析

lodash源码中debounce函数分析

一、使用

在lodash中我们可以使用debounce函数来进行防抖和截流,之前我并未仔细注意过,但是不可思议的是,lodash中的防抖节流函数是一个函数两用的,所以今天我就简单分析一下,它是如何做到的;

lodash中的debounce官网用法

// 情况一:当resize事件触发后,并不会立即执行,而是会直到密集程度大于150的时候,才会触发calculateLayout执行;也就是我们常说的防抖函数;
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 

// 情况二:当点击时 `sendMail` 随后就被调用。此后的300毫秒内触发的将会被忽略,300毫秒之后的触发才会生效,又会计算一个新的周期;这就是我们常说的节流函数;
jQuery(element).on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));


通过上面的分析我们会发现,在同一个函数中,实现了防抖和节流的效果;

二、源码分析

先来认识一下一部分的准备代码;


const freeGlobal = typeof global === 'object' && global !== null && global.Object === Object && global;
// 这是用来判断当前环境的;实际上在浏览器环境下;global指向window;

函数中,如果未定义wait的情况下会优先使用requestAnimationFrame动画api; 否则就使用setTimeout;


const useRAF = (!wait && wait !== 0 && typeof root.requestAnimationFrame === 'function');

整个debounce函数形如下面的结构;闭包了一部分的全局变量;然后返回一个函数,函数执行逻辑根据闭包的全局变量为依据;实际上我们写的很多高阶函数都需要借助这样的思想;


function debounce (a , b){
  let c,d,e;
  return function (){
    let res = use(c,d,e);
    // todo something...
  }
}

在lodash中节流的思路是这样子的;先提供两个闭包的变量leading , trailing ;leading控制是否是节流函数; trailing控制是否是防抖函数;这里我们先讨论节流的思路;返回的函数肯定是一直会被触发的,因此我们需要做到的是,第一次触发时,直接执行,此后触发的直接忽略,直到超过预定等待时间后,触发的才执行,实际上相当于将密集的触发,稀疏成为一定的周期触发一次,这就是所谓的节流;

那我们就需要先办法实现一个函数;能够判断当前的函数是否应该实行;这个函数可以这样写;


function shouldInvoke (time) {
  const timeSinceLastCall = time - lastCallTime;
  const timeSinceLastInvoke = time - lastInvokeTime;
  return (lastCallTime === undefined || (timeSinceLastCall >= wait))
}

它表达的意思可以是每次将当前时间与上一次触发的时间做比较,如果差值大于预定周期,那么就说明可以执行;要么是第一次执行,上一次触发的时间是undefined,这个函数也会执行;

整体的代码可以像下面这样;


function debounce (func, wait, options) {
  let lastArgs,
    lastThis,
    maxWait,
    result,
    timerId,
    lastCallTime;

  let lastInvokeTime = 0
  let leading = false
  let maxing = false
  let trailing = true

  if (typeof func !== 'function') {
    throw new TypeError('Expected a function')
  }
  wait = +wait || 0
  if (isObject(options)) {
    leading = !!options.leading
    trailing = 'trailing' in options ? !!options.trailing : trailing
  }

  function invokeFunc (time) {  // invoke : 调用的意思;
    const args = lastArgs
    const thisArg = lastThis

    lastArgs = lastThis = undefined
    lastInvokeTime = time  // 每一次这个函数的执行时间,就是更新全局lastInvokeTime的时间至函数执行的时刻;
    result = func.apply(thisArg, args)  // func的执行内部this指向全局的this , 参数列表指向lastArgs;
    return result
  }

  function leadingEdge (time) {
    lastInvokeTime = time
    return leading ? invokeFunc(time) : result
  }

  function shouldInvoke (time) {
    const timeSinceLastCall = time - lastCallTime
    const timeSinceLastInvoke = time - lastInvokeTime
    return (lastCallTime === undefined || (timeSinceLastCall >= wait))
  }


  function debounced (...args) {
    const time = Date.now()
    const isInvoking = shouldInvoke(time) // true

    lastArgs = args
    lastThis = this
    lastCallTime = time
    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime)
      }
    }
    return result
  }
  return debounced
}

所以节流的思想其实很简单,就是对于每一次单位时间的触发,如果符合条件,调用,不符合条件,忽略,是否符合条件的关键在于当前调用时间与第一次触发的时间的时间差是否大于预定周期;

三、防抖函数

lodash中的防抖函数写的就比较麻烦了,一般我们自己实现的思路,可以是这个样子;

先定义一个wait时间内执行的定时器,然后如果触发频率大于了wait就直接执行这个定时器所注册的函数;如果没有,就清除当前定义的定时器;从新从触发时间开始计时的期限为wait周期的定时器;等价于不断推进一个wait周期的定时器;这种思路是可以的;但是lodash实现的方式并非这样;它是第一次触发的时候开始了一个wait周期的定时器;然后每次触发,并不清除定时器,而是保存着触发的时间;然后在wait周期后判断是否执行注册的函数;判断的标准就是看当前时间和保存的时间差是否大于wait,如果大于或者等于就直接执行函数,否则就看一下,差值是多少,再次定义一个差值的定时器,再次检验,通过这样的方式,就可以最终检验到是否可以执行函数;达到防抖的目的;它的核心有下面几段;


function leadingEdge (time) {
  // Reset any `maxWait` timer.
  lastInvokeTime = time
  // Start the timer for the trailing edge.
  timerId = startTimer(timerExpired, wait)
  // Invoke the leading edge.
  return leading ? invokeFunc(time) : result
}


function timerExpired () {
  const time = Date.now()
  if (shouldInvoke(time)) {
    return trailingEdge(time)
  }
  // Restart the timer.
  timerId = startTimer(timerExpired, remainingWait(time))
}

function startTimer (pendingFunc, wait) {
  if (useRAF) {
    root.cancelAnimationFrame(timerId)
    return root.requestAnimationFrame(pendingFunc)
  }
  return setTimeout(pendingFunc, wait)
}


function remainingWait (time) {
  const timeSinceLastCall = time - lastCallTime
  const timeSinceLastInvoke = time - lastInvokeTime
  const timeWaiting = wait - timeSinceLastCall // 主要是这一个

  return maxing
    ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)
    : timeWaiting
}

四、完整代码


function debounce (func, wait, options) {
  let lastArgs,
    lastThis,
    maxWait,
    result,
    timerId,
    lastCallTime;

  let lastInvokeTime = 0
  let leading = false
  let maxing = false
  let trailing = true

  // Bypass `requestAnimationFrame` by explicitly setting `wait=0`.
  const useRAF = (!wait && wait !== 0 && typeof root.requestAnimationFrame === 'function') // 看一下当前环境是否可以使用requestAnimationFrame

  if (typeof func !== 'function') {
    throw new TypeError('Expected a function')
  }
  wait = +wait || 0
  if (isObject(options)) {
    leading = !!options.leading
    maxing = 'maxWait' in options
    maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : maxWait // 配置项中的maxWait和wait更大的那一个;
    trailing = 'trailing' in options ? !!options.trailing : trailing
  }

  function invokeFunc (time) {  // invoke : 调用的意思;
    const args = lastArgs
    const thisArg = lastThis

    lastArgs = lastThis = undefined
    lastInvokeTime = time  // 每一次这个函数的执行时间,就是更新全局lastInvokeTime的时间至函数执行的时刻;
    result = func.apply(thisArg, args)  // func的执行内部this指向全局的this , 参数列表指向lastArgs;
    return result
  }
  // 开始一个任务;
  function startTimer (pendingFunc, wait) {
    if (useRAF) {
      root.cancelAnimationFrame(timerId)
      return root.requestAnimationFrame(pendingFunc)
    }
    return setTimeout(pendingFunc, wait)
  }
  // 结束一个任务;
  function cancelTimer (id) {
    if (useRAF) {
      return root.cancelAnimationFrame(id)
    }
    clearTimeout(id)
  }

  function leadingEdge (time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time
    // Start the timer for the trailing edge.
    timerId = startTimer(timerExpired, wait)
    // Invoke the leading edge.
    return leading ? invokeFunc(time) : result
  }

  function remainingWait (time) {
    const timeSinceLastCall = time - lastCallTime
    const timeSinceLastInvoke = time - lastInvokeTime
    const timeWaiting = wait - timeSinceLastCall

    return maxing
      ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)
      : timeWaiting
  }

  function shouldInvoke (time) {
    const timeSinceLastCall = time - lastCallTime
    const timeSinceLastInvoke = time - lastInvokeTime
    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait))
  }

  function timerExpired () {
    const time = Date.now()
    if (shouldInvoke(time)) {
      return trailingEdge(time)
    }
    // Restart the timer.
    timerId = startTimer(timerExpired, remainingWait(time))
  }

  function trailingEdge (time) {
    timerId = undefined

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (trailing && lastArgs) {
      return invokeFunc(time)
    }
    lastArgs = lastThis = undefined
    return result
  }

  function cancel () {
    if (timerId !== undefined) {
      cancelTimer(timerId)
    }
    lastInvokeTime = 0
    lastArgs = lastCallTime = lastThis = timerId = undefined
  }

  function flush () {
    return timerId === undefined ? result : trailingEdge(Date.now())
  }

  function pending () {
    return timerId !== undefined
  }

  function debounced (...args) {
    const time = Date.now()
    const isInvoking = shouldInvoke(time) // true
    lastArgs = args
    lastThis = this
    lastCallTime = time
    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime)
      }
      if (maxing) {
        // Handle invocations in a tight loop.
        timerId = startTimer(timerExpired, wait)
        return invokeFunc(lastCallTime)
      }
    }
    if (timerId === undefined) {
      timerId = startTimer(timerExpired, wait)
    }
    return result
  }
  debounced.cancel = cancel
  debounced.flush = flush
  debounced.pending = pending
  return debounced
}


  • 10
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值