js节流和防抖

节流(throttle): 指连续触发事件的函数,在一定时间间隔内只执行一次。

function throttle(fn, delay) {
  let timer = null;
  return function() {
    const self = this;
    const args = arguments;
    if (!timer) {
      timer = setTimeout(function() {
        timer = null;
        fn.apply(self, args);
      }, delay)
    }
  }
}

//使用
window.addEventListener('scroll', throttle(function() {
  console.log('scroll')
}, 1000))
防抖(debounce): 如果在一定时间内再次触发,就会取消上一的操作,重新执行最新的操作。

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

//使用
window.addEventListener('input', debounce(function() {
  console.log('input')
}, 1000))

 

posted @ 2023-04-26 09:37  变形金刚之猩猩将军  阅读(24)  评论(0编辑  收藏  举报