js 防抖节流

防抖:比如一个点击事件频繁触发只执行最后一次

节流:频繁触发固定时间执行(设置一秒执行一次,10秒点一千下还是执行10次)

<script>
  window.onload = function(){
    var btn = document.getElementById("btn");

    function debounce(fn,delay){
        let timer //借助闭包
        return function() {   
          if(timer){ //为空为声明
                clearTimeout(timer)  //声明为定时器没执行就
            }
            timer = setTimeout(fn,delay) // 声明为定时器
           }
        }
        // 然后是旧代码
        function showTop() {
          console.log('被点击')
        }

     // 第一种 通过点击事件
    //  btn.onclick =  debounce(showTop,1000)
     function throttle(fn,delay){
        let valid = true
        return function() {
            if(!valid){
                console.log('重复滚动'+valid)
                return false 
            }
            // 工作时间,执行函数并且在间隔期内把状态位设为无效
              valid = false
              setTimeout(() => {
                  fn()
                  valid = true;  //一秒一次函数执行完成让重复滚动不组织
              }, delay)
          }
     }  

     function showTop  () {
        console.log('到点执行');
      }
      btn.onclick  = throttle(showTop,1000) 


  }
</script>
<body>
  <button id="btn">点击</button>
  </body>

https://segmentfault.com/a/1190000018428170

原文地址:https://www.cnblogs.com/BKY88888888/p/15629693.html