10.节流.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. -->
  26. <div id="box"></div>
  27. <script>
  28. var box = document.getElementById("box");
  29. let x = 0;
  30. function CountMain() {
  31. box.innerText = x++;
  32. }
  33. // 防抖
  34. function throttle(fn, delay) {
  35. var timer = null;
  36. return function () {
  37. if (!timer) {
  38. timer = setTimeout(function () {
  39. fn();
  40. timer = null;
  41. }, delay)
  42. }
  43. }
  44. }
  45. box.addEventListener('click', throttle(CountMain, 5000))
  46. </script>
  47. </body>
  48. </html>