节流-throttle的两种实现方法

防抖和节流的区别:

防抖:只执行最后一次

节流:只执行第一次

什么是节流?

节流是指单位时间内,如果频繁触发事件,只执行一次

例子:王者荣耀技能冷却,冷却时间内点击技能不会有作用。

使用场景: 鼠标移动mousemove,页面尺寸缩放resize,滚动条滚动scroll等。

案例

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

方法1:lodash库的_.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++
      // 如果里面存在大量操作 dom 的情况,可能会卡顿
    }
    box.addEventListener('mousemove', _.throttle(mouseMove, 500))


  </script>
</body>

</html>

法2:手写节流函数

效果图:

<!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>
        const box = document.querySelector('.box')
        let i = 1  // 让这个变量++
        // 鼠标移动函数
        function mouseMove() {
            box.innerHTML = i++
        }
        // 节流的核心就是利用定时器来实现
        // 1.声明一个定时器变量
        // 2.当鼠标每次滑动都先判断是否有定时器了,如果有定时器则不开启新的定时器
        // 3.如果没有定时器就开启新的定时器,存到变量里面
        // 3.1定时器里面调用执行的函数
        // 3.2定时器里面要把定时器清空
        function throttle(fn, t) {
            let timer = null
            return function () {
                if (!timer) {
                    timer = setTimeout(function () {
                        fn()
                        // 清空定时器
                        timer = null
                    }, t)

                }

            }
        }
        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" />
  <meta name="referrer" content="never" />
  <title>综合案例</title>
  <style>
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    .container {
      width: 1200px;
      margin: 0 auto;
    }

    .video video {
      width: 100%;
      padding: 20px 0;
    }

    .elevator {
      position: fixed;
      top: 280px;
      right: 20px;
      z-index: 999;
      background: #fff;
      border: 1px solid #e4e4e4;
      width: 60px;
    }

    .elevator a {
      display: block;
      padding: 10px;
      text-decoration: none;
      text-align: center;
      color: #999;
    }

    .elevator a.active {
      color: #1286ff;
    }

    .outline {
      padding-bottom: 300px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="header">
      <a href="http://pip.itcast.cn">
        <img src="https://pip.itcast.cn/img/logo_v3.29b9ba72.png" alt="" />
      </a>
    </div>
    <div class="video">
      <video src="https://v.itheima.net/LapADhV6.mp4" controls></video>
    </div>
    <div class="elevator">
      <a href="javascript:;" data-ref="video">视频介绍</a>
      <a href="javascript:;" data-ref="intro">课程简介</a>
      <a href="javascript:;" data-ref="outline">评论列表</a>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
  <script>
    // 1. 获取元素  要对视频进行操作
    const video = document.querySelector('video')
    video.ontimeupdate = _.throttle(() => {
      // console.log(video.currentTime) 获得当前的视频时间
      // 把当前的时间存储到本地存储
      localStorage.setItem('currentTime', video.currentTime)
    }, 1000)

    // 打开页面触发事件,就从本地存储里面取出记录的时间, 赋值给  video.currentTime
    video.onloadeddata = () => {
      // console.log(111)
      video.currentTime = localStorage.getItem('currentTime') || 0
    }
  </script>
</body>

</html>

 

参考:黑马教程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在前端开发中,throttle(节流)是一种优化性能的技术,用于限制函数的执行频率。它可以确保一个函数在一定时间间隔内只被执行一次。在给定的时间间隔内,如果多次触发了该函数,只有第一次触发会立即执行,后续的触发会被忽略,直到时间间隔过去后,再次触发时才会执行。这样可以减少函数的执行次数,避免资源的浪费和性能的下降。 在给出的引用中,有三个例子展示了throttle的实现方式。和是两种常见的方法,分别使用了时间戳和定时器来实现节流。其中,使用时间戳记录上次触发的时间,并通过与当前时间的差值判断是否满足时间间隔,如果满足则执行函数。使用定时器,在函数执行后设置一个定时器,当定时器触发时执行函数,如果在定时器触发前再次触发了函数,则清除之前的定时器重新设置。 另外,是一种防抖(debounce)的例子,与节流类似,但是在时间间隔内的触发会重新计时,只有在一定时间内没有再次触发时才会执行函数。 需要注意的是,节流和防抖都是根据实际需求来选择使用的,具体使用哪种方式要根据具体的场景和需求来确定。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [前端性能优化——节流(throttle)](https://blog.csdn.net/weixin_43371610/article/details/100101268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [js 函数防抖(debounce)函数节流(throttle)](https://blog.csdn.net/qq_27009517/article/details/118381886)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值