Reputation: 8492
I was looking for a solution to a problem and I found this aswer https://stackoverflow.com/a/6962808/2724978
The function written is:
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
setTimeout(function() {
doSomething();
loop();
}, rand);
}());
My question is, why is the function insite parenthesis an also having () at the end? It got me a bit confused, never seen this before.
Upvotes: 1
Views: 94
Reputation: 31270
The snippet creates an anonymous function, and immediately calls it.
The problem with doing without parens,
// This is a syntax error
function () {
something;
}();
is that that is a syntax error; because the statement starts with 'function', the parser expects a function name to follow. Wrapping it all in parens makes it syntatically legal to define an anonymous function there.
// This is valid syntax
(function () {
something;
}());
Upvotes: 1
Reputation: 11431
This is an example of an Immediately Invoked Function Expression.
The link above will explain all you need to know, but essentially there are two things happening.
()
) immediately afterwards ensures the scope of that expression is sealed.Upvotes: 3