抖动debounce和节流throttle

抖动:主要针对窗口resize变化,防止短时间内一直触发,比较耗性能。

/**es5写法*/
function debounce(method,delay){
    var timer = null;
    return function(){
        var context = this,args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function(){
            method.apply(context,args);
        },delay);
    }
}
/**vue- es6写法*/
export function debounce(func, delay) {
  let timer

  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

节流:主要针对输入搜索框,实时搜索内容,去后端实时请求,影响性能。

function throttle(method, delay, time) {
     var timeout,startTime = +new Date();
     return function() {
         var context = this,
         args = arguments,
         curTime = +new Date();
         clearTimeout(timeout);
         // 如果达到了规定的触发时间间隔,触发 handler
         if (curTime - startTime >= time) {
           method.apply(context, args);
           startTime = curTime;
       } else {
           // 没达到触发间隔,重新设定定时器
           timeout = setTimeout(method, delay);
     }
};

猜你喜欢

转载自blog.csdn.net/pinhmin/article/details/128702585