先不纠结防抖节流的概念,就问这两种有什么区别,第一种是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;
};
};
上面两种有什么区别?
建议你弄弄清楚什么叫节流,什么叫防抖
而且这也不是递归
前面那个是防抖,后面那个是节流