23.防抖节流.html 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. background: aqua;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div id="box">1</div>
  17. <script>
  18. var box = document.getElementById("box");
  19. /**
  20. * 防抖:
  21. * 原理:当事件触发时,设置一个延迟时间,
  22. * 在延迟时间内如果再次触发事件,则重新计时,直到延迟时间结束才开始执行函数
  23. * 作用:防止函数被频繁的调用,适用于调整窗口的大小,搜索框连续输入
  24. *
  25. */
  26. // function shake(fn, timer) {
  27. // let time = null;
  28. // return function () {
  29. // if (time) {
  30. // clearTimeout(time);
  31. // }
  32. // time = setTimeout(() => {
  33. // fn();
  34. // }, timer);
  35. // };
  36. // }
  37. // function count() {
  38. // console.log(box.innerText += 1)
  39. // }
  40. // console.log(box,'box')
  41. // box.addEventListener("click",shake(count,2000))
  42. /**
  43. * 节流:
  44. * 原理:在规定的一定时间内 函数只能执行一次 无论鼠标触发多少次
  45. */
  46. function throttle(fn, time) {
  47. let timer = null;
  48. return function () {
  49. if (!timer) {
  50. timer = setTimeout(() => {
  51. fn();
  52. }, time);
  53. }
  54. };
  55. }
  56. function count() {
  57. console.log((box.innerText += 1));
  58. }
  59. console.log(box, "box");
  60. box.addEventListener("click", throttle(count, 2000));
  61. </script>
  62. </body>
  63. </html>