您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页Js — 防抖及底层实现

Js — 防抖及底层实现

来源:伴沃教育

防抖:单位时间内,频繁触发事件,只执行最后一次

防抖实现方式:

  • lodash提供的防抖函数_.debounce(func,[wait=0],[option=])
  • 定时器setTimeout

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

_.debounce函数

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: #ccc;
      color: #fff;
      text-align: center;
      font-size: 100px;
    }
  </style>
</head>

<body>
  <div class="box"></div>
  <script src="lodash.min.js"></script>
  <script>
    const box = document.querySelector('.box')
    let i = 1  // 让这个变量++
    // 鼠标移动函数
    function mouseMove() {
      box.innerHTML = i++
    }
    
    //语法:_.debounce(fun,时间)
    box.addEventListener('mousemove', _.debounce(mouseMove, 500))

  </script>
</body>

</html>

定时器(底层)

思路:

  • 先声明一个定时器变量
  • 每次鼠标移动(事件触发)的时候都要先判断是否有定时器,如果有就先清除以前的定时器

  • 如果没有定时器则开启定时器,记得存到变量里面
  • 在定时器里面调用要执行的函数 
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      height: 500px;
      background-color: #ccc;
      color: #fff;
      text-align: center;
      font-size: 100px;
    }
  </style>
</head>

<body>
  <div class="box"></div>
  <script src="lodash.min.js"></script>
  <script>
    const box = document.querySelector('.box')
    let i = 1  // 让这个变量++
    // 鼠标移动函数
    function mouseMove() {
      box.innerHTML = i++
    }
    
    // box.addEventListener('mousemove', _.debounce(mouseMove, 500))

    function debounce(fn,t){
        //1.
        let timer
        //return 返回一个匿名函数
        return function(){
            //2.3.4
            if(timer) clearTimeout(timer)
            timer = setTimeout(function(){
            //在定时器里执行要执行的函数mouseMove()
                fn()
            }, t)
        }
    }

    // 为什么返回一个匿名函数?
    // debounce(mouseMove, 500)单写这个是函数调用;只执行一次
    // debounce(mouseMove, 500) 接收 function(){2,3,4}
    // 就相当于box.addEventListener('mousemove',function(){2,3,4})
    box.addEventListener('mousemove',debounce(mouseMove, 500))

  </script>
</body>

</html>

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务