防抖

JavaScript专题之跟着underscore学防抖

第一版

function debounce(func, wait) {
  var timeout;
  return function () {
    clearTimeout(timeout);
    timeout = setTimeout(func, wait);
  }
}

第二版

this绑定

function debounce(func, wait) {
  var timeout;

  return function () {
    var context = this;
    
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      func.apply(context);
    }, wait);
  }
}

event对象

function debounce(func, wait) {
  var timeout;

  return function () {
    var context = this;
    var args = arguments;
  
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      func.apply(context, args)
    }, wait);
  }
}

立即执行

function debounce(func, wait, immediate) {
  var timeout;

  return function () {
    var context = this;
    var args = arguments;

    if (timeout) clearTimeout(timeout);

    if (immediate) {

      var callNow = !timeout;
      timeout = setTimeout(function() {
        timeout = null;
      }, wait);
      if (callNow) func.apply(context, args)
    }
    else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
    
  }
}

返回值

function debounce(func, wait, immediate) {
  var timeout, result;

   return function () {
      var context = this;
      var args = arguments;

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

取消

function debounce(func, wait, immediate) {
  var timeout, result;

  var debounced = function () {
      var context = this;
      var args = arguments;
    
      if (timeout) clearTimeout(timeout);
      if (immediate) {

        var callNow = !timeout;
         timeout = setTimeout(function() {
            timeout = null;
          }, wait)
          if (callNow) result = func.apply(context, args)
      } else {
        timeout = setTimeout(function() {
          func.apply(context, args)
        }, wait)
      }
      return result;
  }
  debounced.cancel = function() {
    clearTimeout(timeout);
    timeout = null;
  }
  return debounced;
}

使用:

var count = 1;
var container = document.getElementById('container');

function getUserAction() {
    container.innerHTml = count++;
 }

var setUserAction = debounce(getUserAction, 1000, true);

container.onmounsemove = setUseAction;

document.getElementById('button').addEventListener('click', function() {
  setUseAction.cancel();
})

你可能感兴趣的:(防抖)