防抖和节流

2019-07-10  本文已影响0人  kim_jin

概念

实现方式

防抖的实现方式:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <button id="dobounce">点我防抖</button>
    <button id="throttle">点我节流!</button>
    <script>
      window.onload = function() {
        // 进行 防抖
        var myDebounce = document.getElementById("dobounce");
        myDebounce.addEventListener("click", dobounce(saydoDounce));
        // 进行 节流
        var myThrottle = document.getElementById("throttle");
        myThrottle.addEventListener("click", throttle);
      };

      // 防抖
      function dobounce(fn) {
        let timeout = null;
        return function() {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            // fn();
            // console.log(this)
            fn.call(this);
          }, 1000);
        };
      }
      function saydoDounce() {
        console.log(this);
        console.log("防抖成功");
      }

      // 方法一
      // 节流
      // function throttle(fn){
      //     let canRun = true;
      //     return function(){
      //         if(!canRun){ // 在函数开头判断标志是否为 true,不为 true 则中断函数
      //             return;
      //         }
      //         canRun = false;
      //         setTimeout(()=>{
      //             fn.call(this);
      //             canRun = true;
      //         },2000)
      //     }
      // }


      // 方法二
      let canRun = true;

      function throttle() {
        //   console.log(canRun)
          if (!canRun) {
            // 在函数开头判断标志是否为 true,不为 true 则中断函数
            return;
          }
          canRun = false;
          setTimeout(() => {
            sayThrottle();
            canRun = true;
          }, 5000);
      }

      function sayThrottle() {
        console.log("节流成功");
      }
    </script>
  </body>
</html>

防抖的代码:这件事儿需要等待,如果你反复催促,我就重新计时!
节流的代码:固定时间内只是执行一次

上一篇 下一篇

猜你喜欢

热点阅读