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 = "哈哈"
        }
  • 相关阅读:
    jQuery获取Select选择的Text和 Value(转)
    android学习---EditText
    android学习---Activity
    android学习---LinearLayout
    android学习---布局Layout
    android颜色码制表
    java面试题二
    java面试题一
    基本排序算法java实现
    Integer与int的区别
  • 原文地址:https://www.cnblogs.com/styleFeng/p/14193569.html
Copyright © 2011-2022 走看看