# 防抖

  • 对于一些高频触发操作的场景,我们需要加防抖操作。比如:监听页面滚动、输入实时显示搜索结果等。这些都需要加防抖操作,不然对页面性能有很大的副作用。
  • 简单概括:防抖就是将高频操作优化为最后一次执行。

实现:

// 防抖
const debounce = (fn, wait, immediate = false) => {
  let timer = null;
  return function () {
    let context = this,
      args = arguments;
    if (immediate && !timer) {
      fn.apply(context, args);
    }
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, wait)
  }
}

# 节流

每段时间后执行一次,将高频转化为低频。

// 节流
const throttle = (fn, wait, immediate = false) => {
  let timer = null;
  return function () {
    let context = this,
      args = arguments;
    if (immediate && !timer) {
      fn.apply(context, args);
    }
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(context, args);
        timer = null;
      }, wait)
    }
  }
}