Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked


The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.


  • debounce返回的是debounced function)
  • func被调用的时机:最后一次的debounced func 被调用后再过wait 毫秒 就执行func 函数
  • 以下举例:也就是说,如果我连续快速的一直resize窗口,那么calculateLayout方法一直不会被执行。calculateLayout只会在resize操作停止后的150ms后才执行

      



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


Creates a throttled function that only invokes func at most once per every wait milliseconds.


The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

     




requestAnimationFrame:

  • 如果为wait 为0,


$(window).on('scroll',debounce(report,2000,{trailing:true,leading:false}))

time

第N+K次滚动事件

trailing?

leading?

立即执行report()

yes

2秒后执行report()

yes

>2s

第N次滚动事件

抖动:

每2次滚动事件的间隔都在2秒内


第N+K + 1次滚动事件

调用report 的时机:

function shouldInvoke(time) {
  var timeSinceLastCall = time - lastCallTime, //距离上次调用debounce函数的时间(也就是距离上次scroll事件发生的时间)
  timeSinceLastInvoke = time - lastInvokeTime;//距离上次调用report的时间

  // Either this is the first call, activity has stopped and we're at the
  // trailing edge, the system time has gone backwards and we're treating
  // it as the trailing edge, or we've hit the `maxWait` limit.
    return lastCallTime === undefined    //第一次滚动
          ||(timeSinceLastCall >= wait)  //距离上次滚动超过2秒(@note:这里是去抖动的关键)
          ||(timeSinceLastCall < 0)  //系统时钟出错
          ||(maxing && timeSinceLastInvoke >= maxWait);//距离上次调用report函数超过maxWait

参数:

wait: scroll事件发生间隔小于wait则视为抖动,不会执行report方法

option:

  • maxWait

> 2s

throttle

/**每隔wait执行一次callback*/
function throttle(callback,wait) {
    var timeId = undefined;
    return function(){
        var args = arguments;
        if(timeId) {
            return;
        }
        timeId = setTimeout(function(){
            callback.apply(this,args);
            timeId = undefined;
        },wait);
    }

}
debounce/throttle

debounce/throttle

2018-12-12 19:49:28 2 462
这里是评论

相关推荐