I was reading a post about how to fire a function after a window resize was complete and came across some examples that assigned self executing anonymous functions to variables:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function() {
delay(function(){
alert('Resize...');
//...
}, 500);
});
What is the difference/benefit of making the function operand self executing as opposed to it’s traditional use? i.e.
var delay = function() { ...
The main reason for this is namespacing variables. Functions introduce a new variable scope. In the case of the above example,
timeris not clobbering the global namespace while still being available to the code that needs it.Since I apparently need to clarify:
The goal is to have a variable outside the function:
Because if the variable would be inside the function, it would be reinitialized every time. We want a persistent value outside the function though.
In the above code
timeris a global variable though. We don’t want that. To avoid that, we close the variable up in a new scope so it’s accessible to thedelayfunction, but not globally:delayis now a function just as before which can usetimeroutside itself, yettimeris not in the global scope.