mervynyang
1/9/2018 - 6:21 AM

throttle

throttle

function throttle(fn, delay = 200) {
  let now
  let lastExec
  let timer
  let context
  let args

  const execute = () => {
    fn.apply(context, args)
    lastExec = now
  }

  return (...callArgs) => {
    context = this
    args = callArgs

    now = Date.now()

    if (timer) {
      clearTimeout(timer)
      timer = null
    }

    if (lastExec) {
      const diff = delay - (now - lastExec)
      if (diff < 0) {
        execute()
      } else {
        timer = setTimeout(() => {
          execute()
        }, diff)
      }
    } else {
      execute()
    }
  }
}

export default throttle