e 1 сар өмнө
parent
commit
0e3d1ae565

+ 65 - 0
4.js高级/23.防抖节流.html

@@ -0,0 +1,65 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Document</title>
+    <style>
+      #box {
+        width: 300px;
+        height: 300px;
+        background: aqua;
+      }
+    </style>
+  </head>
+  <body>
+    <div id="box">1</div>
+    <script>
+      var box = document.getElementById("box");
+      /**
+       * 防抖:
+       * 原理:当事件触发时,设置一个延迟时间,
+       * 在延迟时间内如果再次触发事件,则重新计时,直到延迟时间结束才开始执行函数
+       * 作用:防止函数被频繁的调用,适用于调整窗口的大小,搜索框连续输入
+       *
+       */
+      //   function shake(fn, timer) {
+      //     let time = null;
+      //     return function () {
+      //       if (time) {
+      //         clearTimeout(time);
+      //       }
+      //       time = setTimeout(() => {
+      //         fn();
+      //       }, timer);
+      //     };
+      //   }
+
+      //   function count() {
+      //     console.log(box.innerText += 1)
+      //   }
+      //   console.log(box,'box')
+      //   box.addEventListener("click",shake(count,2000))
+      /**
+       * 节流:
+       * 原理:在规定的一定时间内 函数只能执行一次 无论鼠标触发多少次
+       */
+      function throttle(fn, time) {
+        let timer = null;
+        return function () {
+          if (!timer) {
+            timer = setTimeout(() => {
+              fn();
+            }, time);
+          }
+        };
+      }
+
+      function count() {
+        console.log((box.innerText += 1));
+      }
+      console.log(box, "box");
+      box.addEventListener("click", throttle(count, 2000));
+    </script>
+  </body>
+</html>