防抖与节流的简单理解

防抖(debounce)与节流(throttle)的概念在一开始很容易混淆,但其实只要认真理解了就不是很难区分。

打个通俗的比喻,防抖相当于回城,每次被打断,就需要重新执行回城的操作,只有真正不受干扰时才能完成回城;而节流相当于技能冷却,在施放了一次技能操作后,只有等到规定时间后才能施放下一次技能,这期间就是键盘或鼠标按烂了也无法施放技能,即施放技能的频率是定死的。

我们可以通过防抖节流的简单例子-----按键防抖与节流来帮助理解其概念

目标:主要实现每次鼠标点击触发计数增加的对应防抖和节流效果

1.页面结构

<!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>
</head>
<body>
    <button class="btn1">防抖请求+1</button>
    <button class="btn2" style="margin-left: 10px;">节流请求+1</button>
<script>
      const btn1 = document.querySelector('.btn1')
      const btn2 = document.querySelector('.btn2')
      let a = 0,b = 0
</script>
</body>
</html>

 2.防抖代码

    // 防抖方法
      function debounce(func,delay){
        let timer = null
        return function(...args){
          // 事件再次触发就清除定时器,打断函数执行
          clearTimeout(timer)
          timer = setTimeout(()=>{
            func.apply(this,args)
          },delay)
        }
      }

3.节流代码

      // 节流方法一
      function throttle(func,delay){
        // 设置节流阀
        let flag = true
        return function(...args){
          if(flag){
           // 关闭节流阀
            flag = false
            // 执行函数
            func.apply(this,args)
            setTimeout(()=>{
              // 定时时间结束就打开节流阀
              flag = true
            },delay)
          }
        }
      }
      // 节流方法二
       function throttle(func,delay){
       // 设置节流阀
         let timer = null
          return function(...args){
       // 只要定时器在执行就关闭节流阀,退出函数执行
            if(timer) return
            timer = setTimeout(()=>{
               func.apply(this,args)
       // 等定时时间结束就再次清空定时器,打开节流阀
                timer = null
             },delay)
          
         }
       }

4.执行函数

      function addA(){
          a++
          console.log('防抖请求计数值为',a);
      }
      function addB(){
          b++
          console.log('节流请求计数值为',b);
      }

5.代码总览

<!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>
</head>
<body>
    <button class="btn1">防抖请求+1</button>
    <button class="btn2" style="margin-left: 10px;">节流请求+1</button>
    <script>
      const btn1 = document.querySelector('.btn1')
      const btn2 = document.querySelector('.btn2')
      let a = 0,b = 0
      btn1.addEventListener('click',debounce(addA,1000))
      btn2.addEventListener('click',throttle(addB,1000))

    // 防抖方法
      function debounce(func,delay){
        let timer = null
        return function(...args){
          // 事件再次触发就清除定时器,打断函数执行
          clearTimeout(timer)
          timer = setTimeout(()=>{
            func.apply(this,args)
          },delay)
        }
      }
      // 节流方法一
      function throttle(func,delay){
        // 设置节流阀
        let flag = true
        return function(...args){
          if(flag){
           // 关闭节流阀
            flag = false
            // 执行函数
            func.apply(this,args)
            setTimeout(()=>{
              // 定时时间结束就打开节流阀
              flag = true
            },delay)
          }
        }
      }
      // 节流方法二
      // function throttle(func,delay){
      // 设置节流阀
      //   let timer = null
      //   return function(...args){
      //  只要定时器在执行就关闭节流阀,退出函数执行
      //     if(timer) return
      //      timer = setTimeout(()=>{
      //         func.apply(this,args)
      // 等定时时间结束就再次清空定时器,打开节流阀
      //          timer = null
      //       },delay)
          
      //   }
      // }
      function addA(){
          a++
          console.log('防抖请求计数值为',a);
      }
      function addB(){
          b++
          console.log('节流请求计数值为',b);
      }
    </script>
</body>
</html>

6.实现效果

(1)防抖按键:无论鼠标点的多快,只有在点击停下间隔一秒后,才能正常输出递增的数值,否则都不会执行递增和输出操作。

(2)节流按键:无论鼠标点的多快,都会以固定的频率输出递增的数值,输出间隔时间就是给节流函数设置的延时时间,这里设置的是一秒。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaScript 中,防抖(debouncing)和节流(throttling)是两种优化高频率触发事件的方法,可以减少代码的执行次数,提高性能。 防抖 防抖是指在事件被频繁触发时,只有在一定时间内没有新的触发事件才会执行事件处理函数。在这段时间内,如果事件又被触发,则重新计时。 防抖的实现思路是:在事件处理函数执行前,设置一个定时器,如果在定时器时间内再次触发了事件,则清除原定时器并重新设置一个新的定时器,如此反复。如果在定时器时间内没有再次触发事件,则执行事件处理函数。 防抖的应用场景包括:搜索框输入、窗口调整等需要频繁触发事件时,可以通过防抖来减少事件处理函数的执行次数。 示例代码: ```javascript function debounce(func, delay) { let timer = null; return function () { const context = this; const args = arguments; clearTimeout(timer); timer = setTimeout(function () { func.apply(context, args); }, delay); }; } const searchInput = document.getElementById("search-input"); const searchHandler = function () { console.log("执行搜索操作"); }; searchInput.addEventListener("input", debounce(searchHandler, 500)); ``` 上面的代码中,`debounce` 函数接受一个事件处理函数和一个时间间隔作为参数,返回一个新的函数,这个新函数在被调用时会执行事件处理函数,但是在执行前会设置一个定时器,如果在时间间隔内再次被调用,则会清除原定时器并重新设置一个新的定时器。 节流 节流是指在事件被频繁触发时,只有在一定时间间隔内执行一次事件处理函数。在这段时间内,如果事件又被触发,则忽略这次触发。 节流的实现思路是:在事件处理函数执行前,判断距离上一次执行的时间间隔是否超过了指定的时间间隔,如果超过了,则执行事件处理函数并更新上一次执行时间;否则忽略这次事件触发。 节流的应用场景包括:页面滚动、DOM 元素拖拽等需要频繁触发事件时,可以通过节流来减少事件处理函数的执行次数。 示例代码: ```javascript function throttle(func, delay) { let lastTime = 0; return function () { const context = this; const args = arguments; const now = new Date().getTime(); if (now - lastTime >= delay) { func.apply(context, args); lastTime = now; } }; } const scrollHandler = function () { console.log("执行页面滚动操作"); }; window.addEventListener("scroll", throttle(scrollHandler, 500)); ``` 上面的代码中,`throttle` 函数接受一个事件处理函数和一个时间间隔作为参数,返回一个新的函数,这个新函数在被调用时会执行事件处理函数,但是在执行前会判断距离上一次执行的时间间隔是否超过了指定的时间间隔,如果超过了,则执行事件处理函数并更新上一次执行时间;否则忽略这次事件触发。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值