防抖&节流

简介: 防抖&节流

防抖

在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行

防抖实现

注意以下几点

  1. this 的指向
  2. 是否可以立即执行
  3. 函数的参数问题
  4. 函数具有返回值的问题
  5. 添加取消功能
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;
}

节流

持续触发事件,每隔一段时间,只执行一次事件。

节流实现

// 第四版
function throttle(func, wait, options) {
  var timeout, context, args, result;
  var previous = 0;
  if (!options) options = {};

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

  var throttled = function () {
    var now = new Date().getTime();
    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;
      func.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
  };
  throttled.cancel = function () {
  clearTimeout(timeout);
  previous = 0;
  timeout = null;
};
  return throttled;
}
目录
相关文章
|
3月前
节流、防抖
节流、防抖
21 2
|
3月前
|
前端开发 UED
关于防抖和节流的理解
防抖和节流是前端开发中常用的两种性能优化技术。
23 0
|
12月前
什么是防抖和节流,怎么实现一个防抖和节流?
功能:当事件被触发N秒之后再执行回调,如果在N秒内被触发,则重新计时。
|
JavaScript 前端开发
节流与防抖
节流与防抖
36 0
|
JavaScript 前端开发
什么是防抖和节流?如何实现防抖和节流?
防抖(debounce)和节流(throttle)是 JavaScript 中常用的两种性能优化方法。
|
前端开发 JavaScript
关于防抖和节流我所知道的
关于防抖和节流我所知道的
47 0
|
缓存 JavaScript
防抖和节流
防抖和节流