9.节流.html 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. color: #ff0;
  12. font-size: 30px;
  13. font-weight: 800;
  14. text-align: center;
  15. line-height: 200px;
  16. background: #f00;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <div id="box"></div>
  22. <!--
  23. 节流:
  24. 限制函数在一定时间内的执行次数
  25. 规定n秒内连续点击事件但只执行一次
  26. 鼠标移动 鼠标跟踪 窗口大小 频繁点击按钮
  27. 在固定时间间隔内,函数最多只执行一次。无论事件触发多少次,都保证在指定时间内只执行一次。
  28. -->
  29. <script>
  30. var box = document.getElementById("box");
  31. console.log(box, box.innerHTML)
  32. // count +1
  33. let i = 1
  34. function Count() {
  35. box.innerText = i++;
  36. }
  37. function throttle(fn, delay) {
  38. var timer = null;
  39. return function () {
  40. if (!timer) {
  41. timer = setTimeout(function () {
  42. fn();
  43. timer = null;
  44. }, delay)
  45. }
  46. }
  47. }
  48. box.addEventListener('click', throttle(Count, 3000))
  49. /**
  50. * 防抖与节流的区别:
  51. * 节流 保证函数在固定时间间隔内至少执行一次
  52. * 防抖 在事件停止触发一段时间后才执行
  53. */
  54. </script>
  55. </body>
  56. </html>