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?