防抖,节流写法

<body>
  <div id="app">
    <button class="btn">我是防抖函数</button>
  </div>
  <script>
    document.querySelector('.btn').addEventListener('click',debounce(handle,1000))
    function debounce(fn,t){
      let time = null
      return function(){
        if(time != null){
          clearTimeout(time)
        }
        time = setTimeout(fn,t)
      }
    }
    function handle(){
      console.log(1111)
    }
  </script>
</body>
 
 
 
<body>
    <div id="app">
        <button class="btn">我是节流函数</button>
    </div>
    <script>
        document.querySelector('.btn').addEventListener('click',throttle(handle,2000))
        function throttle(fn,t){
            let flag = true
            return function(){
                if(!flag)return
                flag = false
                setTimeout(()=>{
                    fn()
                    flag = true
                },t)
            }
        }
        function handle(){
            console.log(111)
        }
    </script>
</body>
 
写几遍你会感谢我的
posted @ 2019-02-15 18:30  国服第一李师师  阅读(361)  评论(0编辑  收藏  举报