js手写防抖和节流

189 阅读1分钟

JS手写防抖

//节流函数和防抖函数是我们在开发中为了节约性能经常会使用到的函数,这里分享两个自己就可以手写出的简单的方法.
const input = document.querySelector('.input') //html文件中写一个类名为input的输入框监听它的input事件
console.log(input)

function debounce(func, t) {
//func表示需要防抖的事件, t表示延迟时间
    let timerId;
  
    return function() {
      const context = this;
      const args = arguments;
  
      clearTimeout(timerId);
  
      timerId = setTimeout(function() {
        func.apply(context, args);
      }, t);
    };
  }
function fn() {
    console.log('今天是个好日子')
}
input.addEventListener('input',debounce(fn, 3000) )

// debounce(fn, 3000)

JS手写节流函数

function throttle(func, delay) {
  let timerId;
  let lastInvokeTime = 0;

  return function() {
    const context = this;
    const args = arguments;
    const currentTime = Date.now();

    if (currentTime - lastInvokeTime >= delay) {
      clearTimeout(timerId);

      func.apply(context, args);
      lastInvokeTime = currentTime;
    } else {
      clearTimeout(timerId);

      timerId = setTimeout(function() {
        func.apply(context, args);
        lastInvokeTime = currentTime;
      }, delay - (currentTime - lastInvokeTime));
    }
  };
}


使用:

// 原始函数
function handleScroll() {
  // 处理逻辑
  console.log('Scroll event');
}

// 创建节流函数
const throttleScroll = throttle(handleScroll, 200);

// 监听滚动事件
window.addEventListener('scroll', throttleScroll);