手写防抖、节流

概念:

  • 防抖:事件触发n秒后再执行回调,若在n秒内事件又被触发,则重新计时
  • 节流:在指定时间内,只能有一次触发事件的回调执行,若在单位时间内重复触发则不生效

应用场景:

  • 防抖:输入框输入(input)…
  • 节流:浏览器窗口变化(resize)、页面滚动(scroll)、拖拽(drag)…

防抖:

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

**节流:

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

调用:

const btn = document.querySelector('button')
btn.addEventListener('click', debounce(function () {
  console.log('发财小手点个关注')
}, 1000, true))

猜你喜欢

转载自blog.csdn.net/qq_37215621/article/details/131482929