| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <!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 throttle(fn, delay) {
- // 闭包
- var timer = null;
- return function () {
- if (!timer) {
- timer = setTimeout(function () {
- fn();
- timer = null;
- }, delay)
- }
- }
- }
- // box.onclick = function() {
- // fn1()
- // }
- box.addEventListener("click", throttle(fn1, 3000))
- </script>
- </body>
- </html>
|