Skip to content

Conversation

@XiaoWinter
Copy link

I found a throttling method in the comments section that passed all the current tests but was wrong.So I added a test case to find this type of error.With this wrapping method, if the interval between two calls is greater than 1000ms, the wrapped method becomes invalid.

function throttle(func, period) {
  let savedArgs
  let savedThis
  let start = true

  function runFunc() {
    if (savedArgs) {
      func.apply(savedThis, savedArgs)
      savedArgs = undefined
      setTimeout(runFunc, period)
    }
  }

  function wrapper(...rest) {
    savedThis = this
    savedArgs = rest
    if (start) {
      start = false
      runFunc()
    }
  }
  return wrapper
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants