JS手写节流防抖

46 阅读1分钟

节流

节流就是每隔一段时间只能执行一次函数。

使用场景:用户频繁点击按钮。

const click = () => {
  console.log("按钮被点击");
};

const throttle=(fn,delay)=> {
  let timer;
  return (...args) =>{
    if (timer) { return; }
    fn.call(undefined,...args);
    timer = setTimeout( ()=> {
      timer = null;
    }, delay);
  };
};

防抖

使用场景:用户频繁做拖动操作,等用户停止拖动后在执行操作。

const drag = () => {
  console.log("拖拽结束");
};

function debounce(fn,delay) {
  let timer;
  return function () {
    let context = this
    let args=arguments
    clearTimeout(timer)
    timer = setTimeout(function() {
      fn.apply(context, args);;
    }, delay);
  }
}