According the underscore documentation:
throttle_.throttle(function, wait)
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
What does it means Useful for rate-limiting events that occur faster than you can keep up with
.
This function is equivalent to setTimeout with a function that calls itself?
Can someone provide me some example on jsfiddle?
The difference between throttle and debounce is described here: https://css-tricks.com/the-difference-between-throttling-and-debouncing/
/*
"Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
"Perhaps a function is called 1,000 times in a quick burst, dispersed over 3 seconds, then stops being called. If you have debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds, once the burst is over. Each time the function is called during the burst it resets the debouncing timer."
*/
_.debounce = (fn, delay) => {
let timer
return (...args) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(null, args)
}, delay)
}
}
/*
"Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
*/
_.throttle = (fn, delay) => {
let canCall = true
return (...args) => {
if (canCall) {
fn.apply(null, args)
canCall = false
setTimeout(() => {
canCall = true
}, delay)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With