29.防抖和节流.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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: 400px;
  10. height: 400px;
  11. background: #ff0;
  12. color: #f00;
  13. font-size: 30px;
  14. text-align: center;
  15. line-height: 300px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div class="box"></div>
  21. <script>
  22. // var box = document.querySelector(".box");
  23. // var i = 1;
  24. // function count() {
  25. // // i++ 先赋值 后自增
  26. // box.innerHTML = i++;
  27. // }
  28. // box.addEventListener("mousemove",count);
  29. /**
  30. * 防抖和节流
  31. * 防抖:
  32. * 优点:就是指触发事件在n秒内只执行一次函数;
  33. * 缺点:如果在规定的时间内不断触发 我们的方法就会不断延迟;
  34. * 节流:
  35. * 指在规定n秒连续点击事件但只执行一次;
  36. */
  37. /**防抖代码*/
  38. var box = document.querySelector(".box");
  39. var i = 1;
  40. function count() {
  41. // i++ 先赋值 后自增
  42. box.innerHTML = i++;
  43. }
  44. // 防抖函数部分
  45. function debounce(fn,time) {
  46. var timer = null;
  47. return function() {
  48. if(timer) clearTimeout(timer);
  49. timer = setTimeout(function(){
  50. fn();
  51. },time);
  52. }
  53. }
  54. box.addEventListener("click",debounce(count,500));
  55. /**节流代码*/
  56. // var box = document.querySelector(".box");
  57. // var i = 1;
  58. // function count() {
  59. // // i++ 先赋值 后自增
  60. // box.innerHTML = i++;
  61. // }
  62. // function throttle(fn,time) {
  63. // var timer = null;//没有值
  64. // return function() {
  65. // if(!timer) { //没有值
  66. // timer = setTimeout(function(){
  67. // fn();
  68. // timer = null;
  69. // },time)
  70. // }
  71. // }
  72. // }
  73. // box.addEventListener("click",throttle(count,1000));
  74. /**
  75. * 防抖和节流的区别:
  76. * 节流:轮播图数表多次点击,鼠标移动,页面尺寸,滚动事件...
  77. * 防抖:输入框搜索...
  78. */
  79. </script>
  80. </body>
  81. </html>