【js】手写防抖和节流

1.防抖:n秒后执行该事件,如果事件在n秒内触发,则重新计时

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

}

2.节流:n秒只执行一次,若在n秒内触发,只有一次生效

function throttle(fn,wait){
  let timer = null
  return function(){
   let _this = this
   let args = arguments
   if(!timer){
     timer=setTimeout(()=>{
       fn.apply(_this,args)
      },wait)
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_56489154/article/details/125983013