美文网首页
throttle(节流)

throttle(节流)

作者: 砚婉儿 | 来源:发表于2020-10-13 13:19 被阅读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)

相关文章

网友评论

      本文标题:throttle(节流)

      本文链接:https://www.haomeiwen.com/subject/unxjpktx.html