手写一个防抖、节流

130 阅读1分钟

防抖

要点

  • clearTimeout 取消定时器
  • return timers 闭包缓存 定时器地址,用于判断
const db = (fn, delay) => {
  let timer
  let timers = () => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn()
    }, delay)
  }
  return timers
}

// 测试
function fn (a, b ,c) {
  console.log(a, b ,c)
  this.a = a
}

let aa = db(() => {
  console.dir(new fn(1, 2, 3))
}, 300)

document.addEventListener('click', aa)

节流

要点

  • clearTimeout 取消定时器
  • timer = null 销毁数据
  • return timers 闭包缓存 定时器地址,用于判断
const tt = (fn, delay) => {
  let timer;
  return () => {
    if (!timer) {
      timer = setTimeout(() => {
        clearTimeout(timer);
        timer = null;
        fn();
      }, delay);
    }
  };
};

function fn (a, b ,c) {
  console.log(a, b ,c)
  this.a = a
}

let aa = tt(() => {
  console.dir(new fn(1, 2, 3))
}, 1000)

document.addEventListener('click', aa)