Skip to content

节流

js
function throttle(func, limit) {
  let lastFunc
  let lastRan

  return function (...args) {
    const context = this

    if (!lastRan) {
      func.apply(context, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(function () {
        if (Date.now() - lastRan >= limit) {
          func.apply(context, args)
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}

// Example usage:
const handleScroll = () => {
  console.log('Scroll event fired')
}

const throttledScroll = throttle(handleScroll, 200)

window.addEventListener('scroll', throttledScroll)