I am interested in the \"debouncing\" function in javascript, written here : http://davidwalsh.name/javascript-debounce-function
Unfortunately the code is not explai
What you want to do is the following: If you try to call a function right after another, the first should be cancelled and the new one should wait for a given timeout and then execute. So in effect you need some way of cancelling the timeout of the first function? But how? You could call the function, and pass the returning timeout-id and then pass that ID into any new functions. But the solution above is way more elegant.
What it does is effectively make the timeout
variable available in the scope of returned function. So when a 'resize' event is fired it does not call debounce()
again, hence the timeout
content is not changed (!) and still available for the "next function call".
The key thing here is basically that we call the internal function every time we have a resize event. Perhaps it is more clear if we imagine all resize-events is in an array:
var events = ['resize', 'resize', 'resize'];
var timeout = null;
for (var i = 0; i < events.length; i++){
if (immediate && !timeout) func.apply(this, arguments);
clearTimeout(timeout); // does not do anything if timeout is null.
timeout = setTimeout(function(){
timeout = null;
if (!immediate) func.apply(this, arguments);
}
}
You see the timeout
is available to the next iteration?
And there is no reason, in my opinion to rename this
to content
and arguments
to args
.