throttle(节流)

2020-10-13  本文已影响0人  砚婉儿

高频时间触发,但n秒内只会执行一次,所以节流会稀释函数的执行频率。
常应用于鼠标不断点击触发、监听滚动事件。

方法:

function throttle(func, ms = 1000) {
  let canRun = true
  return function (...args) {
    if (!canRun) return
    canRun = false
    setTimeout(() => {
      func.apply(this, args)
      canRun = true
    }, ms)
  }
}

// 测试
const task = () => { console.log('run task') }
const throttleTask = throttle(task, 1000)
window.addEventListener('scroll', throttleTask)
上一篇 下一篇

猜你喜欢

热点阅读