# 防抖(debounce)和节流(throttle)

防抖和节流主要是用户交互性能优化常用的方案,防抖指用户一段时间内连续操作只会触发一次,节流指用户一段时间内操作只会按照一定频率进行触发。

常用使用场景;

  • scroll 滚动触发大量事件,会加剧性能问题。可以通过防抖节流限制触发频率。
  • click 点击事件,用户可能短时间内多次提交表单数据,造成数据重复提交到后台。
  • input 输入事件, 如果通过输入事件触发自动补全建议,这些建议事件可能是通过后台接口获取的。频繁请求数据可能会造成服务器压力过大。
  • 触摸事件, 鼠标移动事件等等。。

# 防抖(debounce)

多次点击试试效果!

function debounce(fn, delay = 200) {
  let timer = null;

  return function() {
    // 保存执行上下文
    const context = this;

    // 获取fn 调用参数
    const args = arguments;

    // 通过timeout 延迟执行函数, 如果二次输出则取消上次 timer
    if (timer !== null) clearTimeout(timeout);

    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

# 节流(throttle)

多点击几次看看效果

function throttle(fn, thresholds = 200) {
  let timer = null;

  let now = +new Date();

  let last = null;

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

    // 如果当前触发时间小于 上次+频率 时间内,则重置为最新定时器
    // 否者, 达到频率, 直接触发函数执行
    if (last && now < last + thresholds) {
      if (timer != null) return;
      timer = setTimeout(() => {
        last = now;
        fn.apply(context, args);
        timer = null;
      }, thresholds);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}
上次更新: 7/29/2020, 11:06:06 PM