Explorar el Código

节流与防抖

DESKTOP-MK04A0R\chuck hace 3 años
padre
commit
90ed496a2c
Se han modificado 3 ficheros con 54 adiciones y 0 borrados
  1. 28 0
      04/index.html
  2. 25 0
      04/src/bind.js
  3. 1 0
      README.md

+ 28 - 0
04/index.html

@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <style>
+        body{
+            height:2000px;
+        }
+    </style>
+</head>
+<body>
+    <input type="text">
+    <script src="./src/bind.js"></script>
+    <script>
+        window.addEventListener('scroll',throttle(function(e){
+            console.log(e)
+        },500))
+
+        let input = document.querySelector('input')
+        input.onkeydown = debounce(function(e){
+            console.log(e.keyCode)
+        },1000)
+    </script>
+</body>
+</html>

+ 25 - 0
04/src/bind.js

@@ -0,0 +1,25 @@
+
+//节流 -- 立即执行回调
+function throttle(callback,wait){
+    let start = 0;
+    return function(e){
+        let now = Date.now()
+        if(now - start >= wait){
+            callback.call(this,e)
+            start = now
+        }
+    }
+}
+//防抖 -- 事件触发时不会立即触发回调
+function debounce(callback,time){
+    let timer = null
+    return function(e){
+        if(timer){
+            clearTimeout(timer)
+        }
+        timer = setTimeout(()=>{
+            callback.call(this,e)
+            timer = null
+        },time)
+    }
+}

+ 1 - 0
README.md

@@ -2,6 +2,7 @@
 * 01 call函数封装实现
 * 02 apply函数封装实现
 * 03 bind函数封装实现
+* 04 函数节流与防抖
 
 ## 运行
 npm i