Skip to content

实现防抖和节流

:::: tabs @tab 防抖函数

js
function debounce(fn, wait) {
  var timer;
  return function () {
    var context = this;
    var args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, wait);
  };
}
function debounce(fn, wait) {
  var timer;
  return function () {
    var context = this;
    var args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, wait);
  };
}

@tab 节流函数

js
function throttle(fn, wait) {
  var pre = 0;
  return function () {
    var now = Date.now();
    var context = this;
    var args = arguments;
    if (now - pre > wait) {
      fn.apply(context, args);
      pre = now;
    }
  };
}
function throttle(fn, wait) {
  var pre = 0;
  return function () {
    var now = Date.now();
    var context = this;
    var args = arguments;
    if (now - pre > wait) {
      fn.apply(context, args);
      pre = now;
    }
  };
}

@tab 节流函数(定时器)

js
function throttle(fn, wait) {
  var timer;
  return function () {
    var context = this;
    var args = arguments;
    if (!timer) {
      timer = setTimeout(function () {
        timer = null;
        fn.apply(context, arguments);
      }, wait);
    }
  };
}
function throttle(fn, wait) {
  var timer;
  return function () {
    var context = this;
    var args = arguments;
    if (!timer) {
      timer = setTimeout(function () {
        timer = null;
        fn.apply(context, arguments);
      }, wait);
    }
  };
}

::::