闭包封装防抖和节流函数

42 阅读1分钟

防抖:用户触发事件过于频繁,只要最后一次事件的操作

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" />

    <script>
      let inp = document.querySelector('input')
      inp.oninput = debounce(function () {
        console.log(this.value)
      }, 500)

      function debounce(fn, delay) {
        let t = null
        return function () {
          if (t !== null) {
            clearTimeout(t)
          }
          t = setTimeout(() => {
            fn.call(this)
          }, delay)
        }
      }
    </script>
  </body>
</html>

节流:控制高频事件执行次数

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        height: 2000px;
      }
    </style>
  </head>
  <body>
    <script>
      // 节流:控制高频事件执行次数
      window.onscroll = throttle(function () {
        console.log(123)
      }, 500)
      function throttle(fn, delay) {
        let flag = true
        return function () {
          if (flag) {
            setTimeout(() => {
              fn.call(this)
              flag = true
            }, delay)
            flag = false
          }
        }
      }
    </script>
  </body>
</html>