Bootstrap

防抖与节流

防抖

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
     <input type="text" id="hInput"></input>
    <script>
    const inputDOM=document.getElementById('hInput')
    function debounce(fn){
     //addEventListner第二个参数为函数,所以这里要返回一个函数return function(){}
     let timer=null
      return function(){
        if(timer){
          clearInterval(timer)
        }
        timer=setTimeout(()=>{
            fn()
        },1000)
      
      }
    }
   inputDOM.addEventListener('input',debounce(()=>{console.log('发送请求数据')}))
    </script>


  </body>
</html>

节流

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
      }
    </style>
  </head>
  <body>
    <!-- <input type="text" id="hInput"></input> -->
    <div class="box" draggable="true"></div>
    <script>
      const boxDOM = document.querySelector(".box");
      function throttle(fn) {
         let timer=null
        return function () {
          if(timer){
            return 
          }
         timer= setTimeout(() => {
            fn();
          }, 200);
        };
      }
      //节流:一段时间内,只执行一次某个操作;过了一段时间后,还有操作的话,继续执行新的操作
      boxDOM.addEventListener(
        "drag",
        throttle(() => {
          console.log("拖拽");
        })
      );
    </script>
  </body>
</html>

;