8.防抖.html 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. -->
  33. <script>
  34. var box = document.getElementById("box");
  35. console.log(box, box.innerHTML)
  36. // count +1
  37. let i = 1
  38. function Count() {
  39. box.innerText = i++;
  40. }
  41. // Count()
  42. // Count()
  43. // Count()
  44. // Count()
  45. // 防抖函数
  46. function debounce(fn, delay) {
  47. var timer = null;
  48. return function () {
  49. if(timer) clearTimeout(timer);
  50. timer = setTimeout(function () {
  51. fn()
  52. }, delay)
  53. }
  54. }
  55. box.addEventListener('click', debounce(Count, 3000))
  56. </script>
  57. </body>
  58. </html>