| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <!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;
- text-align: center;
- line-height: 300px;
- color: #ff0;
- font-size: 30px;
- background-color: #f00;
- }
- </style>
- </head>
- <body>
- <div id="box"></div>
- <script>
- /**
- * 防抖:
- * 点击事件 在事件触发后 等待一段时间在执行回调函数
- * 在等待的时间内 若再次点击事件 则重新触发事件 重新计时
- * 搜索框输入 滚动事件 resize窗口大小
- */
- const box = document.getElementById("box");
- let x = 0;
- function CountMain() {
- box.innerHTML = ++x;
- }
- function debounce(fn, delay) {
- let timer = null;
- return function () {
- if (timer) clearTimeout(timer);
- timer = setTimeout(function () {
- fn();
- }, delay)
- }
- }
- box.addEventListener("click", debounce(CountMain, 3000))
- </script>
- </body>
- </html>
|