美文网首页
防抖与节流

防抖与节流

作者: 张宪宇 | 来源:发表于2022-12-18 09:52 被阅读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('发起请求')
    }
    
    

    相关文章

      网友评论

          本文标题:防抖与节流

          本文链接:https://www.haomeiwen.com/subject/ymgjqdtx.html