5.防抖.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. font-size: 30px;
  15. background-color: #f00;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="box"></div>
  21. <script>
  22. /**
  23. * 防抖:
  24. * 点击事件 在事件触发后 等待一段时间在执行回调函数
  25. * 在等待的时间内 若再次点击事件 则重新触发事件 重新计时
  26. * 搜索框输入 滚动事件 resize窗口大小
  27. */
  28. const box = document.getElementById("box");
  29. let x = 0;
  30. function CountMain() {
  31. box.innerHTML = ++x;
  32. }
  33. function debounce(fn, delay) {
  34. let timer = null;
  35. return function () {
  36. if (timer) clearTimeout(timer);
  37. timer = setTimeout(function () {
  38. fn();
  39. }, delay)
  40. }
  41. }
  42. box.addEventListener("click", debounce(CountMain, 3000))
  43. </script>
  44. </body>
  45. </html>