【手撸代码】简单聊聊防抖节流

173 阅读1分钟

防抖

概念:在触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间,通俗来说就是在某一时间内,避免让一个函数执行的太频繁,让其只执行最后一次

应用场景

  • 例如在淘宝上的商品搜索,在用户输入的时候如果不做防抖,会重复请求一些没必要的数据,从而浪费性能,加上防抖之后在用户输入最后的关键字之后再去请求需要的资源
  • 在监听页面窗口大小
  • 监听滚动事件
<!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>01-防抖</title>
  </head>
  <body>
    <input type="text" />
    <script>
      const dom = document.querySelector('input')
      dom.addEventListener('input',debounce(changeInput,500))
      function debounce(fn, time) {
        let timer = null
        return function () {
          let args = arguments
          clearTimeout(timer)
          timer = setTimeout(() => {
            fn.apply(this, args)
          }, time)
        }
      }
      function changeInput() {
        console.log('打印')
      }
    </script>
  </body>
</html>

节流

概念:当触发事件后,n秒之后才能再次触发事件,n秒时间内是无法重新触发的,

应用场景

  • 轮播图轮播的时候使用节流,避免多次点击连续快速切换
  • 监听鼠标移动事件,减少事件触发
  • 发送验证码案例
<!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>
      html,body {
        height: 100%;
        background-color: aquamarine;
      }
    </style>
  </head>
  <body>
    
    <script>
      // 没有节流的数字
      let notThrottle = 0
      // 节流的数字
      let num = 0
      // 获取body
      const body = document.body
      // 节流函数
      function throttle(fn, time) {
        let timer = null
        return function () {
          if (!timer) {
            const args = arguments
            timer = setTimeout(() => {
              fn.apply(this, args)
              timer = null
            }, time)
          }
        }
      }
      // 没有节流的
      body.addEventListener('mousemove',function(){
        console.log('没有节流的' + notThrottle++)
      })
      // 节流的
      body.addEventListener('mousemove',throttle(function(){
        console.log('节流的' + num++)
      },1000))
    </script>
  </body>
</html>