Skip to content

如何实现一个能立即执行,且可以取消的节流 #83

Description

@inkjuncom
function throttle(fn, delay) {
  let timer = null
  let lastTime = 0

  const throttled = function (...args) {
    const now = Date.now()

    if (now - lastTime >= delay) {
      lastTime = now
      fn.apply(this, args)
    }

    clearTimeout(timer)
    timer = setTimeout(() => {
      lastTime = 0
    }, delay)
  }

  throttled.cancel = function () {
    clearTimeout(timer)
    lastTime = 0
    timer = null
  }

  return throttled
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions