防抖中这两种实现有啥区别

先不纠结防抖节流的概念,就问这两种有什么区别,第一种是underscore的实现

 _.now = function (){return new Date().getTime()};
_.debounce = function(func, wait, immediate){
    var timeout, args, context, timestamp, result; 
    var later = function(){
        var last = _.now() - timestamp; 
        if (last < wait && last >= 0) { 
            timeout = setTimeout(later, wait - last); // 递归
        }else{
            timeout = null;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
        }
    };
    return function(){ 
      context = this; 
      args = arguments; 
      timestamp = _.now(); 
      if (!timeout) 
         timeout = setTimeout(later, wait);
      return result;
    };
};

分割

 _.now = function (){return new Date().getTime()};
_.debounce = function(func, wait, immediate){
    var timeout, args, context, timestamp, result; 
    var later = function(){
        timeout = null; // 不用递归
        result = func.apply(context, args);
        if (!timeout) context = args = null;
    };
    return function(){ 
      context = this; 
      args = arguments; 
      timestamp = _.now(); 
      if (!timeout) 
         timeout = setTimeout(later, wait);
      return result;
    };
};

上面两种有什么区别?

阅读 1.9k
2 个回答

建议你弄弄清楚什么叫节流,什么叫防抖
而且这也不是递归


前面那个是防抖,后面那个是节流

能把节流防抖搞得这么复杂也是佩服

function debounce(fn,delay){
    var timer = null; 
    return function(){
      clearTimeout(timer);
      timer = setTimeout(function(){
        fn.apply(this);
      },delay)
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题