The first function declaration uses an anonymous function to create a closure over the variable timer
and a second anonymous function to avoid polluting the global namespace with timer
. This is a simple and handy technique to implement data hiding and static variables within a function in JavaScript.
This first/outer function typically only gets used once, which is why it is never given a name, but instead is executed immediately as an anonymous function. However, the opposite is true if you needed to be able to create multiple timers for multiple events.
Consider the following:
var delayBuilder = function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
}
Now:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
is equivalent to:
var delay = delayBuilder();
So, if you needed to have multiple delays (more than one timer running at the same time), you could do:
var delay1 = delayBuilder(),
delay2 = delayBuilder(),
...
delayN = delayBuilder();
// And of course, used as:
delay1(callback, ms);
More generalized, you have a function to build functions, in other words funcBuilder
and func
(using "func" since "function" is a reserved word).
var func = funcBuilder(configurationifany);
So, if the function builder was more complex and you wanted a single, throw-away instance of whatever function it was building, you could do
funcBuilder(configurationifany)(etc, etc);
Or in the case of the code that you posted (although this is overkill for simply wrapping setTimeout
but just to continue the example):
delayBuilder()(callback, ms);
It really boils down to usage. If you're not going to use the function builder more than once, there's no sense in keeping it around and executing it as an anonymous function is more appropriate. If you need to build multiple instances of that function, then saving a reference to the function builder makes sense.