节流防抖

记录贴

<button id="throttle">点我节流!</button>

    window.onload = function() {
      // 1、获取按钮,绑定点击事件
      var myThrottle = document.getElementById("throttle");
      myThrottle.addEventListener("click", throttle(sayThrottle));
    }

    // 2、节流函数体
    function throttle(fn) {
      // 4、通过闭包保存一个标记
      let canRun = true;
      let tips = true;
      let timer = null;
      return function () {
        // 5、在函数开头判断标志是否为 true,不为 true 则中断函数
        if(!canRun && !tips) {
          clearTimeout(timer)
        }
        // 6、将 canRun 设置为 false,防止执行之前再被执行
        canRun = false;
        tips = false;
        // 7、定时器
        timer = setTimeout( () => {
          fn.call(this, arguments);
          console.log(this.val)
          // 8、执行完事件(比如调用完接口)之后,重新将这个标志设置为 true
          canRun = true;
        }, 3000);
      };
    }

    // 3、需要节流的事件
    function sayThrottle() {
      console.log("节流防抖成功!");
      this.val = "哈哈"
    }
原文地址:https://www.cnblogs.com/styleFeng/p/14193569.html