9.防抖.html 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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: 300px;
  10. height: 300px;
  11. text-align: center;
  12. line-height: 300px;
  13. color: #ff0;
  14. background: #00f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <!--
  20. 防抖:
  21. 点击事件 在事件触发后 等待一段时间在执行回调函数
  22. 在等待的时间内 若再点击事件 重新触发事件 重新计时
  23. 搜索框输入
  24. 滚动事件
  25. resize窗口大小
  26. -->
  27. <div id="box"></div>
  28. <script>
  29. var box = document.getElementById("box");
  30. let x = 0;
  31. function CountMain() {
  32. box.innerText = x++;
  33. }
  34. // 防抖
  35. function debounce(fn, delay) {
  36. var timer = null;
  37. return function () {
  38. if (timer) clearTimeout(timer);
  39. timer = setTimeout(function () {
  40. fn();
  41. }, delay)
  42. }
  43. }
  44. box.addEventListener('click', debounce(CountMain, 5000))
  45. </script>
  46. </body>
  47. </html>