防抖与节流

Posted by Leonsux on May 30, 2022

防抖与节流都是一种优化高频操作的手段。

比如在搜索框输入关键词时,如果不做处理,输入 “keyword” 会触发 7 次搜索,而实际上有效搜索只有最后一次。

节流(throttle): n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效。 防抖(debounce): n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时。

节流

const throttled = (fn, time) => {
  let timer = null
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, time);
    }
  }
}

const con = param => console.log(param);

const thCon = throttled(con, 1000);

setInterval(() => {
  thCon(100); // 每秒只触发一次
}, 0);

防抖

const debounce = (fn, time, immediate) => {
  let timer = null;
  const _debounce = function(...args) {
    const context = this;
    if (timer) {
      clearTimeout(timer);
    }

    if (immediate) { // 是否立即执行
      const firstCall = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, time);
      if (firstCall) {
        fn.apply(context, args);
      }
    } else {
      timer = setTimeout(() => {
        fn.apply(context, args);
        clearTimeout(timer);
        timer = null;
      }, time);
    }
  }

  return _debounce;
}

const con = param => console.log(param);

const dCon = debounce(con, 1000, false);

dCon(100)
dCon(200)
// 短时间触发两次,取最后一次执行,输出 200

const dConNow = debounce(con, 1000, true);

dConNow(100)
dConNow(200)
// 短时间触发两次,取第一次执行,输出 100