| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <!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: 200px;
- height: 200px;
- color: #fff;
- font-size: 30px;
- background: #00f;
- }
- </style>
- </head>
- <body>
- <div id="box"></div>
- <script>
- var box = document.getElementById("box");
- let x = 0;
- /**
- * 防抖
- * 指的是高频触发事件时 只在最后一次触发 等待指定时间在执行一次函数 重新计时
- * 防止频繁执行代码 减少性能消耗
- *
- */
- function fn1() {
- box.innerText = x++;
- }
- function debounce(fn, delay) {
- // 闭包
- var timer = null;
- return function () {
- if (timer) clearTimeout(timer);
- timer = setTimeout(function () {
- fn()
- }, delay)
- }
- }
- // box.onclick = function() {
- // fn1()
- // }
- box.addEventListener("click", debounce(fn1, 3000))
- </script>
- </body>
- </html>
|