发抖函数(debounce)

防抖:在用户频繁触发某个行为的时候,我们只识别一次即可[开始边界:第一次点击触发 结束边界:等到最后一次触发]
频繁的频率自己来设定

最简单的防抖处理[设置标识判断]

<html>
  <body>
    <button id="submit">点击按钮</button>
  </body>
</html>
<script>
  let submit = document.querySelector('#submit')
  
  // 模拟从服务器获取数据(需要 1000MS)
  const queryData = callback => {
    setTimeout(() => {
      callback('ok')
    }, 1000)
  }
  
  // 最简单的防抖处理[设置标识判断]
  let running = false
  submit.onclick = function () {
    if (running) return
    running = true
    queryData(result => {
      console.log(result)
      running = false
    })
  }
</script>

方案一

<html>
  <body>
    <button id="submit">点击按钮</button>
  </body>
</html>
<script>
  let submit = document.querySelector('#submit')
  
  // 模拟从服务器获取数据(需要 1000MS)
  const queryData = callback => {
    setTimeout(() => {
        callback('ok')
    }, 1000)
  }

  const handle = function handle() {
    queryData(result => {
      console.log(result)
    })
  }
  
  const debounce = function debounce(func, wait = 300) {
        let timer
        // 定时器的返回值是数字
        return function proxy() {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                func()
            }, wait)
        }
    }
    
    submit.onclick = debounce(handle, 500)
</script>

方案二

<html>
  <body>
    <button id="submit">点击按钮</button>
  </body>
</html>
<script>
  let submit = document.querySelector('#submit')
  
  // 模拟从服务器获取数据(需要 1000MS)
  const queryData = callback => {
    setTimeout(() => {
        callback('ok')
    }, 1000)
  }

  const handle = function handle() {
    queryData(result => {
      console.log(result)
    })
  }
  
  /**
   * 函数防抖处理
   * @params
   *    func:最重要执行的函数[必传]
   *    wait:频繁操作的设定时间[默认是300MS]
   *    immediate:设置边界[默认false:结束边界触发   true:开始边界触发]
   */
  const debounce = function debounce(func, wait, immediate) {
    if (typeof func !== 'function') throw new TypeError('func must be function')
    if (typeof wait === 'boolean') {
      immediate = wait
      wait = 300
    }
    if (typeof wait !== 'number') wait = 300
    if (typeof immediate !== 'boolean') immediate = false
    let timer
    // 定时器的返回值是数字
    return function proxy(...params) {
      let runNow = !timer && immediate,
        self = this
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(() => {
        if (timer) {
          clearTimeout(timer)
          timer = null
        }
        // 结束边界触发
        if (!immediate) func.call(self, ...params)
      }, wait)
      // 开始边界触发
      if (runNow) func.call(self, ...params)
    }
  }
    
  submit.onclick = debounce(handle, 500, true)
</script>

你可能感兴趣的:(JavaScript,javascript,前端)