js节流与去抖(一分钟秒懂 throttle 与 debounce)

什么是debounce?

举个例子:
一个input的onChange事件,监听用户输入,当输入停下来的时候,会发起一段请求。(参考百度的做法)
实现如下:

 var debounce = function(func, wait, immediate) {
    var timeout, result;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) result = func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) result = func.apply(context, args);
        return result;
  };

};

什么是throttle?

举个例子:
我们需要在拖拽的过程中监听当前div的位置,很有可能一秒执行几十次,如果我想提升性能,只监听5次怎么办?

var throttle = function(func, wait) {
    var context, args, timeout, result;
    var previous = 0;
    var later = function() {
      previous = new Date;
      timeout = null;
      result = func.apply(context, args);
    };
    return function() {
      var now = new Date;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0) {
        clearTimeout(timeout);
        timeout = null;
        previous = now;
        result = func.apply(context, args);
      } else if (!timeout) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

你可能感兴趣的:(js节流与去抖(一分钟秒懂 throttle 与 debounce))