美文网首页
函数节流与函数防抖

函数节流与函数防抖

作者: 独钓寒江月 | 来源:发表于2019-08-26 10:54 被阅读0次

    什么是函数节流

    打个很形象的比喻来说,函数节流就相当于技能CD,没CD完技能怎么也放不出,CD完之后你随时可以放。

    函数节流:

    var cd = ture
    button.onclick = ()=> {
      if(cd){
        fn()
        cd = false
        setTimeout(()=> {
          cd = ture
        },1000)
      }
    }
    

    然后把它封装成函数

     function throttle(fn, delay){
         let cd= true
         return function(){
             if(cd){
                 fn.apply(this, arguments)
                 cd= false
                 setTimeout(()=>cd= true, delay)
             }
         }
     }
    

    什么是函数防抖

    函数防抖,就相当于给中了debuff,在中一次就重新刷新debuff持续时间,只有持续时间内没有再吃debuff才能消失。

    函数防抖:

    var debuff = null
    button.onclick = ()=> {
      if(debuff){
        window.clearTimeout(debuff)
      }
      debuff = setTimeout(()=> {
        fn()
        debuff = null
      },10000)
    }
    

    同样把它封装成函数

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

    相关文章

      网友评论

          本文标题:函数节流与函数防抖

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