js debounce 实现

debounce 概念:

触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
1.underscore 实现:

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;
   if (!immediate) {
     result = func.apply(context, args);
     if (!timeout) context = args = null;
   }
 }
};
return function() {
 context = this;
 args = arguments;
 timestamp = _.now();
 var callNow = immediate && !timeout;
 if (!timeout) timeout = setTimeout(later, wait);
 if (callNow) {
   result = func.apply(context, args);
   context = args = null;
 }
 return result;
};
};

给TA打赏
共{{data.count}}人
人已打赏
个人中心
今日签到
有新私信 私信列表
搜索