JavaScript手写防抖

// 当事件被触发-会延迟几秒之后在执行回调
// 如果在延迟的几秒内再次触发事件-那么重新执行回调-重新计时
function antiShake(fn,delay){
  let timer
  return function(...args){
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this,args)
    }, delay);
  }
}

// 检测
function test() {
  console.dir('run antiShakeTest')
}
// 屏幕滚动触发事件
window.addEventListener('scroll',antiShake(test,2000))

猜你喜欢

转载自blog.csdn.net/weixin_63836026/article/details/124796004