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

Js — 节流及底层实现

来源:伴沃教育

节流:单位时间内,频繁触发事件,只执行一次

节流实现方式:

  • lodash提供的节流函数_.throttle(func,[wait=0],[options=])

在wait秒内最多执行func一次

也就是说“在wait秒内不管触发多少次,都只调一次func

  • 定时器setTimeout

目标:鼠标在盒子上移动,不管移动多少次,每隔500ms才+1

_.throttle函数

<!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',_.throttle(mouseMove,3000))

  </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++
    }
    
    function throttle(fn,t){
        let timer = null
        return function(){
            if(!timer){
                timer = setTimeout(function(){
                    fn()
                    //清空定时器
                    timer=null
                },t)
            }
        }
    }

    //return个匿名函数,这样才能多次执行;否则是调用的话,它只会执行一次
    box.addEventListener('mousemove',throttle(mouseMove,3000))

  </script>

</body>

</html>

清空定时器为什么采用timer=null;而非clearTimeout(timer)

因为在setTimeout中是无法清除定时器的,因为定时器还在运作;不合理

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

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

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

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