zoukankan      html  css  js  c++  java
  • 节流防抖

    记录贴

    <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 = "哈哈"
        }
  • 相关阅读:
    计算机故障
    线程池&进程池
    机箱-网卡-声卡-显卡-显示器
    scrapy请求传参-BOSS反爬
    计算机硬件-主板
    计算机硬件-内存
    计算机硬件-硬盘
    计算机硬件-CPU
    ZJNU 1223
    ZJNU 1217
  • 原文地址:https://www.cnblogs.com/styleFeng/p/14193569.html
Copyright © 2011-2022 走看看