防抖与节流

2022-12-18  本文已影响0人  张宪宇

防抖=> 将多次操作变成一次

let telInput = document.querySelector('input')
telInput.addEventListener('input',antiShake(demo,2000))

#防抖封装
function antiShake(fn,wait){
  let timeOut = null ;
  return arges =>{
     if(timeOut) cleatTimeout(timeOut)
     timeOut = setTimeout(fn,wait)
  }
}

function demo(){
  console.log('发起请求')
}

节流

let box = document.querySelector('.box')
telInput.addEventListener('touchmove',throttle(demo,2000))

function throttle(event,time){
  let timer = null;
  return function(){
    if(!timer){
      timer = setTimeout(()=>{
        event()
        timer = null
      },time)
    }
  }
}

function demo(){
  console.log('发起请求')
}

上一篇 下一篇

猜你喜欢

热点阅读