6.节流.html 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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: #00f;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="box"></div>
  21. <!--
  22. 节流:
  23. 点击事件 在事件触发后 等待一段时间在执行回调函数
  24. 在等待的时间内 若再次点击事件 则不执行 需要当前回调函数完成后在执行
  25. 高频的按钮点击事件 滚动加载
  26. -->
  27. <script>
  28. const box = document.getElementById("box");
  29. let x = 0;
  30. function CountMain() {
  31. box.innerHTML = ++x;
  32. }
  33. function throttle(fn, delay) {
  34. let timer = null;
  35. return function () {
  36. if (!timer) {
  37. timer = setTimeout(function () {
  38. fn();
  39. timer = null;
  40. }, delay)
  41. }
  42. }
  43. }
  44. box.addEventListener("click", throttle(CountMain, 3000))
  45. </script>
  46. </body>
  47. </html>