views:

125

answers:

3

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
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.
@Eric - Not necessarily....he could have an if/abort style before hitting this, could go either way.
Nick Craver
+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
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
@lark Correct, maybe I should leave a note. Thank you.
alex
+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