简单的去抖(debounce)处理 和 节流(throttle) 附 源码

为什么需要消抖、节流?

原因:事件频繁触发,频繁的操作DOM,或者频繁的向服务器请求数据,严重消耗性能 或导致页面崩溃

  • window对象的resizescroll事件
  • 拖拽时的mousemove事件
  • 射击游戏中的mousedownkeydown事件
  • 文字输入、自动完成的keyup事件

简单debounce的例子:



debounce.js (引用 underscore.js)

function(func, wait, immediate) {
  var timeout, result;
  var later = function(context, args) {
    timeout = null;
    if (args) result = func.apply(context, args);
  };
  var debounced = restArgs(function(args) {
    var callNow = immediate && !timeout;
    if (timeout) clearTimeout(timeout);
    if (callNow) {
      //如果立即调用,就设置一个定时,并且调用下方法。
      timeout = setTimeout(later, wait);
      result = func.apply(this, args);
    } else if (!immediate) {
      //否则,更新定时的时间
      timeout = _.delay(later, wait, this, args);
    }
    return result;
  });
  debounced.cancel = function() {
    clearTimeout(timeout);
    timeout = null;
  };
  return debounced;
};
throttle.js  节流源码 (引用 underscore.js)
function(func, wait, options) {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};

    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };

    var throttled = function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };

    throttled.cancel = function() {
      clearTimeout(timeout);
      previous = 0;
      timeout = context = args = null;
    };

    return throttled;
  };

 

你可能感兴趣的:(前端,js)