How do I restart a function calling it from inside the same function?
+5
A:
Just call the function again, then return, like this:
function myFunction() {
//stuff...
if(condition) {
myFunction();
return;
}
}
The if
part is optional of course, I'm not certain of your exact application here. If you need the return value, it's one line, like this: return myFunction();
Nick Craver
2010-05-31 00:42:17
Hmmm I would not say that the "if" part is optional. Without it, you would end up calling myFunction recursively until overflowing the stack.
Eric J.
2010-05-31 00:56:08
@Eric - Not necessarily....he could have an if/abort style before hitting this, could go either way.
Nick Craver
2010-05-31 00:59:02
+1
A:
You mean recursion?
function recursion() {
recursion();
}
or
var doSomething = function recursion () {
recursion();
}
Note Using this named anonymous function is not advised because of a longstanding bug in IE. Thanks to lark for this.
Of course this is just an example...
alex
2010-05-31 00:42:30
It is very inadvisable to use a named anonymous function, since there is a bug that has persisted throughout all versions of IE that leaks it into the global namespace overriding any functions named there that are the same.
lark
2010-05-31 00:43:43
+2
A:
Well its recommended to use a named function now instead of arguments.callee which is still valid, but seemingly deprecated in the future.
// Named function approach
function myFunction() {
// Call again
myFunction();
}
// Anonymous function using the future deprecated arguments.callee
(function() {
// Call again
arguments.callee();
)();
lark
2010-05-31 00:42:55