js防抖

69 阅读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=, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn">点击</button>
  <br />
  <br />
  <br />
  <br />
  <br />
  参考文档:https://www.bilibili.com/video/BV1vo4y1y7tD?p=16
  <script>
    // 实现通过参数immediate控制执行的时间点;true:开始点击执行;fanse: 停止点击执行
    const { log } = console
    var btn = document.getElementById('btn')
    // btn.onclick = function (params) {
    //   log('点击了')
    // }

    /** 
     * fn 最终需要执行的事件监听
     * wait 事件触发之后多久开始执行
     * immediate 控制执行第一次还是最后一次,false 执行最后一次
    */
    function myDebounce(fn, wait, immediate) {
      if (typeof fn === 'function') throw new Error('fn is not an function') 
      if (typeof wait === 'undefined') wait = 300
      if (typeof wait === 'boolean') {
        immediate = wait
        wait = 300
      }
      if (typeof immediate === 'undefined') immediate = false

      let timer = null
      return function (...args) {
        let self = this,
        init = immediate && !timer // 这里联合timer判断是确保是第一次才执行(第一次timer是null);但为了隔一会点击还能用,所以要在setTimeout中将timer置为null
        clearTimeout(timer)
        log('timer', timer, init)
        timer = setTimeout(() => {
          log('timer2', timer, init)
          log('执行了')
          timer = null
          !immediate ? fn.apply(this, args) : null // 注意这里用的是immediate,没用init 是防止停止点击还执行一遍;如果想开始点击执行一遍停止点击再执行一遍则这里用init
        }, wait)
        // 如果想要实现只在第一次执行,那么可以添加上 timer 为 null 做为判断
        // 因为只要 timer 为 Null 就意味着没有第二次....点击
        init ? fn.apply(this, args) : null
      }
    }
    function btnClick(ev) {
      log('点击了', this, ev)
    }
    btn.onclick = myDebounce(btnClick, 1000, false)
  </script>
</body>
</html>