Jhey Tompkins
1 min readFeb 24, 2018

--

Hey Enzo Borg Frantz 👋

Whilst technically it would make sense to do that, it would actually yield an undesired behavior 😢

inThrottle is actually not necessary. It’s presence is more of a convenience for comprehension. Setting inThrottle to false either in the setTimeout function or before will either yield the throttle to not throttle or will result in the throttled function firing twice when it fires 👎 This can be tested in the demo.

That first part of the conditional that checks for !inThrottle will only ever fire the one time to make sure that the the first invocation is not throttled. In the invocations after that, as you correctly state, inThrottle is true but we get the desired behavior due to checking the value of lastRan against Date.now().

Therefore, it would make sense to refactor 👍 The simplest refactor being to remove inThrottle and replace with a check against the value of lastRan.

const throttle = (func, limit) => {
let lastFunc
let lastRan
return function() {
const context = this
const args = arguments
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))
}
}
}

That’s a good spot and thanks for raising it, I’ll update this in the article 👍

--

--

Jhey Tompkins
Jhey Tompkins

Written by Jhey Tompkins

I make awesome things for awesome people!

No responses yet