8.防抖.html 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. #box {
  9. width: 200px;
  10. height: 200px;
  11. text-align: center;
  12. line-height: 200px;
  13. font-size: 30px;
  14. font-weight: bold;
  15. color: #ff0;
  16. background: #00f;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <!--
  22. 防抖:
  23. 点击事件,在事件触发后,等待一段时间执行回调函数,
  24. 在等待时间中,再次点击事件,重新出发事件,重新计时
  25. 触发事件后,延迟n秒后执行回调函数,如果在n秒中再次出发事件,则重新计时
  26. 场景:
  27. 1.搜索框输入
  28. 2.调整窗口大小(resize)
  29. 3.滚动事件
  30. -->
  31. <div id="box"></div>
  32. <script>
  33. var box = document.getElementById("box");
  34. let i = 0;
  35. function Count() {
  36. box.innerText = i++;
  37. }
  38. // 防抖
  39. function debounce(fn,delay) {
  40. var timer = null;
  41. return function() {
  42. if(timer) clearTimeout(timer);
  43. timer = setTimeout(function(){
  44. fn()
  45. },delay)
  46. }
  47. }
  48. box.addEventListener('click',debounce(Count,3000));
  49. </script>
  50. </body>
  51. </html>