0


性能优化之防抖

方法1:利用lodash库提供的防抖来处理

方法2:手写一个防抖函数来处理

需求:鼠标在盒子上移动,鼠标停止500ms之后,里面的数字才会变化+1

方法一:利用lodash库实现防抖

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .box{
  10. width: 500px;
  11. height: 500px;
  12. background-color: #ccc;
  13. color: #fff;
  14. text-align: center;
  15. font-size: 100px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <script src="./js/lodash.min.js"></script>
  21. <div class="box"></div>
  22. <script>
  23. // 利用防抖实现性能优化
  24. // 需求:鼠标在盒子上移动,鼠标停止500ms之后,里面的数字就会变化+1
  25. const box = document.querySelector('.box')
  26. let i = 1
  27. function mouseMove(){
  28. box.innerHTML = i++
  29. }
  30. // mousemove鼠标移动事件
  31. // 鼠标一移动就500ms后就触发debounce事件,i就++
  32. // _.debounce语法(fun,时间)
  33. box.addEventListener('mousemove', _.debounce(mouseMove,500))
  34. </script>
  35. </body>
  36. </html>

方法二: 手写一个防抖函数来处理

思路:

  1. 核心是利用setTimeout定时器来实现
  2. 1声明定时器变量
  3. 2每次事件触发时都要先判断是否有定时器,如果有先清除以前的定时器
  4. 3如果没有定时器则开启定时器存入到定时器变量里面
  5. 4定时器里面写函数调用
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .box {
  10. width: 500px;
  11. height: 500px;
  12. background-color: #ccc;
  13. color: #fff;
  14. text-align: center;
  15. font-size: 100px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div class="box"></div>
  21. <script>
  22. // 利用防抖实现性能优化
  23. // 需求:鼠标在盒子上移动,鼠标停止500ms之后,里面的数字就会变化+1
  24. const box = document.querySelector('.box')
  25. let i = 1
  26. function mouseMove() {
  27. box.innerHTML = i++
  28. }
  29. // 手写防抖函数
  30. // 核心是利用setTimeout定时器来实现
  31. // 1声明定时器变量
  32. // 2每次事件触发时都要先判断是否有定时器,如果有先清除以前的定时器
  33. // 3如果没有定时器则开启定时器存入到定时器变量里面
  34. // 4定时器里面写函数调用
  35. function debounce(fn,t){
  36. let timer
  37. //return返回一个匿名函数
  38. return function(){
  39. if(timer) clearTimeout(timer)
  40. timer = setTimeout(function(){
  41. fn() //加小括号调用fn函数
  42. }, t)
  43. }
  44. }
  45. box.addEventListener('mousemove',debounce(mouseMove,500))
  46. // 有括号的函数会直接执行的不用鼠标滑动,所以当鼠标滑动时需要有一个return
  47. </script>
  48. </body>
  49. </html>

标签: 前端 javascript

本文转载自: https://blog.csdn.net/weixin_52512511/article/details/133240764
版权归原作者 要努力奋斗鸭 所有, 如有侵权,请联系我们删除。

“性能优化之防抖”的评论:

还没有评论