i wonder what the difference is between these two declarations:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
function delay {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
}
The first function declaration uses an anonymous function to create a closure over the variable
timerand a second anonymous function to avoid polluting the global namespace withtimer. 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:
Now:
is equivalent to:
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();
More generalized, you have a function to build functions, in other words
funcBuilderandfunc(using “func” since “function” is a reserved word).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
Or in the case of the code that you posted (although this is overkill for simply wrapping
setTimeoutbut just to continue the example):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.