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;
- text-align: center;
- line-height: 200px;
- font-size: 30px;
- font-weight: bold;
- color: #ff0;
- background: #00f;
- }
- </style>
- </head>
- <body>
- <!--
- 防抖:
- 点击事件,在事件触发后,等待一段时间执行回调函数,
- 在等待时间中,再次点击事件,重新出发事件,重新计时
- 触发事件后,延迟n秒后执行回调函数,如果在n秒中再次出发事件,则重新计时
- 场景:
- 1.搜索框输入
- 2.调整窗口大小(resize)
- 3.滚动事件
- -->
- <div id="box"></div>
- <script>
- var box = document.getElementById("box");
- let i = 0;
- function Count() {
- box.innerText = i++;
- }
- // 防抖
- function debounce(fn,delay) {
- var timer = null;
- return function() {
- if(timer) clearTimeout(timer);
- timer = setTimeout(function(){
- fn()
- },delay)
- }
- }
- box.addEventListener('click',debounce(Count,3000));
- </script>
- </body>
- </html>
|