9.节流.html 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. text-align: center;
  12. line-height: 200px;
  13. font-size: 30px;
  14. font-weight: bold;
  15. color: #ff0;
  16. background: #f00;
  17. margin: 20px 0;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <!--
  23. 节流:
  24. 规定时间内,只能触发一次函数,如果在规定时间内再次触发函数
  25. 则不执行,必须等函数完成后才会再次执行
  26. 场景:
  27. 1.高频的按钮点击
  28. 2.滚动加载
  29. -->
  30. <div>
  31. <div id="box"></div>
  32. <div id="box"></div>
  33. <div id="box"></div>
  34. <div id="box"></div>
  35. <div id="box"></div>
  36. <div id="box"></div>
  37. <div id="box"></div>
  38. <div id="box"></div>
  39. <div id="box"></div>
  40. <div id="box"></div>
  41. <div id="box"></div>
  42. </div>
  43. <script>
  44. var box = document.getElementById("box");
  45. let i = 0;
  46. function Count() {
  47. box.innerText = i++;
  48. }
  49. // 时间戳:new Date().getTime() / Date.now()
  50. // 记录上次时间 每次触发时 判断当前时间与上次时间相差是否超过间隔时间
  51. // function throttle(fn,delay) {
  52. // let lastTime = 0
  53. // return function() {
  54. // let now = Date.now();
  55. // setTimeout(function() {
  56. // if(now - lastTime >= delay) {
  57. // fn();
  58. // lastTime = now;
  59. // }
  60. // },delay)
  61. // }
  62. // }
  63. // 定时器
  64. // 设置定时器 在间隔时间后执行回调函数 并在执行后 重置定时器
  65. function throttle(fn, delay) {
  66. let timer = null;
  67. return function () {
  68. if (!timer) {
  69. timer = setTimeout(function () {
  70. fn();
  71. timer = null;
  72. }, delay)
  73. }
  74. }
  75. }
  76. box.addEventListener('click', throttle(Count, 3000));
  77. const handleScroll = throttle(function () {
  78. console.log("滚动位置", window.screenY);
  79. }, 1000)
  80. window.addEventListener('scroll', handleScroll)
  81. </script>
  82. </body>
  83. </html>