26.防抖.html 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 debounce(fn, delay) {
  32. // 闭包
  33. var timer = null;
  34. return function () {
  35. if (timer) clearTimeout(timer);
  36. timer = setTimeout(function () {
  37. fn()
  38. }, delay)
  39. }
  40. }
  41. // box.onclick = function() {
  42. // fn1()
  43. // }
  44. box.addEventListener("click", debounce(fn1, 3000))
  45. </script>
  46. </body>
  47. </html>