8.防抖.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. font-size: 30px;
  12. font-weight: 800;
  13. text-align: center;
  14. line-height: 200px;
  15. color: #f00;
  16. background: #ff0;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <div id="box"></div>
  22. <!--
  23. 防抖:
  24. 当事件触发后,等待一段时间在执行回调函数,
  25. 如果在这段时间内,再次触发事件,则重新计时
  26. 触发事件在n秒内只执行最后一次触发的函数
  27. 执行回调函数 / 延迟时间
  28. 输入框输入内容
  29. 滚动事件
  30. 按钮点击:防止用户多次快速点击
  31. -->
  32. <script>
  33. var box = document.getElementById("box");
  34. console.log(box, box.innerHTML)
  35. // count +1
  36. let i = 1
  37. function Count() {
  38. box.innerText = i++;
  39. }
  40. // Count()
  41. // Count()
  42. // Count()
  43. // Count()
  44. // 防抖函数
  45. function debounce(fn, delay) {
  46. var timer = null;
  47. return function () {
  48. if(timer) clearTimeout(timer);
  49. timer = setTimeout(function () {
  50. fn()
  51. }, delay)
  52. }
  53. }
  54. box.addEventListener('click', debounce(Count, 3000))
  55. </script>
  56. </body>
  57. </html>