27.节流.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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: #fff;
  12. font-size: 30px;
  13. background: #00f;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div id="box"></div>
  19. <script>
  20. var box = document.getElementById("box");
  21. let x = 0;
  22. /**
  23. * 节流
  24. * 规定的时间内 只能触发一次函数 在规定时间内再次触发函数 无效 必须等函数完成后才能在执行
  25. * 防止频繁执行代码 减少性能消耗
  26. *
  27. */
  28. function fn1() {
  29. box.innerText = x++;
  30. }
  31. function throttle(fn, delay) {
  32. // 闭包
  33. var timer = null;
  34. return function () {
  35. if (!timer) {
  36. timer = setTimeout(function () {
  37. fn();
  38. timer = null;
  39. }, delay)
  40. }
  41. }
  42. }
  43. // box.onclick = function() {
  44. // fn1()
  45. // }
  46. box.addEventListener("click", throttle(fn1, 3000))
  47. </script>
  48. </body>
  49. </html>