I want to defer execution of some code on events.
What exactly is the difference between using standard setTimeout
function and a plugin debounce (link to debounce)?
Here's an example with setTimeout
:
var timeout;
$(window).on("scroll", function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
doSomethingFunction();
}, 500);
});
And here's an example with debounce:
$(window).on("scroll",
$.debounce(500, doSomethingFunction)
);
Of course with debounce the code is shorter but are there any other benefits? Which one will be faster?
debounce uses setTimeout internally so the difference is related to the number of times setTimeout is fired. debounce throttles the amount of times it fires setTimeout . If multiple requests are sent in a short duration, only one will come through.
Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() . Use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds have elapsed.
It's simple. They do the exact same thing (rate limiting) except while throttle is being called it'll fire your function periodically, while debounce only fires once at the end. Example: If you're scrolling, throttle will slowly call your function while you scroll (every X milliseconds).
later.
debounce
uses setTimeout
internally so the difference is related to the number of times setTimeout
is fired.
debounce
throttles the amount of times it fires setTimeout
. If multiple requests are sent in a short duration, only one will come through.
var timeout_id = setTimeout(
debounce_mode ? clear
: exec, debounce_mode === undefined ? delay - elapsed
: delay
);
You can review the source code for more information.
The plugin will handle the timeout by setting a timeout id.
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