In the answers to this question someone wisely points out that
The timeout variable stays accessible during every call of the produced function even after debounce itself has returned, and can change over different calls.
It doesn't quite make sense to me. As the timeout variable is local to each call of debounce, it shouldn't be shareable, isn't it?
p.s. Even though it is closure, each call should have a different closure, they just simultaneously all extend their lives after the mother function returns, but they shouldn't talk to each other, right?
Here's the function from the other question:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
function debounce(func, wait, immediate) {
var timeout; //Why is this set to nothing?
return function() {
var context = this,
args = arguments;
clearTimeout(timeout); // If timeout was just set to nothing, what can be cleared?
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args); //This applies the original function to the context and to these arguments?
};
};