9.节流.html 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. <script>
  29. var box = document.getElementById("box");
  30. console.log(box, box.innerHTML)
  31. // count +1
  32. let i = 1
  33. function Count() {
  34. box.innerText = i++;
  35. }
  36. function throttle(fn, delay) {
  37. var timer = null;
  38. return function () {
  39. if (!timer) {
  40. timer = setTimeout(function () {
  41. fn();
  42. timer = null;
  43. }, delay)
  44. }
  45. }
  46. }
  47. box.addEventListener('click', throttle(Count, 3000))
  48. /**
  49. * 防抖与节流的区别:
  50. * 节流 保证函数在固定时间间隔内至少执行一次
  51. * 防抖 在事件停止触发一段时间后才执行
  52. */
  53. </script>
  54. </body>
  55. </html>