函数节流和函数防抖

2021-03-10  本文已影响0人  GL曲终人散

函数节流和函数防抖两者都是优化高频率执行js代码的一种手段。

函数节流

      let flag = true // 设置节流的锁
      const throttle = (fn, delay = 500) => {
        if (flag) {
          // 当锁是打开时,执行对应方法
          fn() // 执行对应方法
          flag = false // 将锁关闭,锁关闭时,不进入if
          setTimeout(function () {
            flag = true // 将锁打开,锁打开时,进入if
          }, delay)
        }
      }

      document.getElementById('aaa').onclick = () => {
        throttle(function () {
          console.log('节流')
        })
      }

函数防抖

      let timer
      const debounce = (fn, delay) => {
        clearTimeout(timer) // 清除上一次还未执行的定时器
        timer = setTimeout(function () {
          fn()
        }, 500)
      }

      document.getElementById('bbb').onclick = () => {
        debounce(function () {
          console.log('防抖')
        })
      }
上一篇 下一篇

猜你喜欢

热点阅读