练习题10_防抖节流.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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: 90vw;
  10. height: 100px;
  11. margin:50px auto;
  12. background: #aaa;
  13. text-align: center;
  14. line-height: 100px;
  15. font-size: 50px;
  16. color: #fff;
  17. font-weight: bold;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <!-- 防抖节流函数 -->
  23. <!-- 防抖函数:在事件触发后等待一段时间,只执行一次函数 如果事件触发后在等待时间内再次触发则清除上一次时间再次等待 -->
  24. <!-- 节流函数:在事件触发后等待一段时间,只执行一次函数 如果事件触发后在等待时间内再次触发则在等待时间内不执行函数 -->
  25. <div class="box" id="box1">0</div>
  26. <div class="box" id="box2">0</div>
  27. <div class="box" id="box3">0</div>
  28. <script>
  29. let box1 = document.getElementById('box1');
  30. let box2 = document.getElementById('box2');
  31. let box3 = document.getElementById('box3');
  32. // 普通事件
  33. box1.onmousemove = function(){
  34. this.innerText = Number(this.innerText) + 1;
  35. }
  36. // 防抖函数
  37. // 两个参数 第一个参数是函数(到时间了要干什么) 第二个参数是等待时间
  38. function debounce(fn,t){
  39. let timer = null;
  40. return function(){
  41. if(timer){
  42. clearTimeout(timer);
  43. }
  44. timer = setTimeout(()=>{
  45. fn();
  46. },t);
  47. }
  48. }
  49. box2.onmousemove = debounce(function(){
  50. box2.innerText = Number(box2.innerText) + 1;
  51. },1000);
  52. // 节流函数
  53. // 两个参数 第一个参数是函数(到时间了要干什么) 第二个参数是等待时间
  54. function throttle(fn,t){
  55. let timer = null;
  56. return function(){
  57. if(timer){
  58. return;
  59. }
  60. timer = setTimeout(()=>{
  61. fn();
  62. timer = null;
  63. },t);
  64. }
  65. }
  66. box3.onmousemove = throttle(function(){
  67. box3.innerText = Number(box3.innerText) + 1;
  68. },1000);
  69. </script>
  70. </body>
  71. </html>