5

How do I restart a function calling it from inside the same function?

FernandoSBS
  • 655
  • 5
  • 12
  • 23
  • 1
    The answers below are sufficient, you just need to take care to have a condition where the function is **not** going to be restarted so you don't get caught in a loop. – stagas May 31 '10 at 00:50

3 Answers3

11

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 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. May 31 '10 at 00:56
  • @Eric - Not necessarily....he could have an if/abort style before hitting this, could go either way. – Nick Craver May 31 '10 at 00:59
3

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();
)();
tbranyen
  • 8,507
  • 1
  • 21
  • 18
1

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...

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 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. – tbranyen May 31 '10 at 00:43
  • @lark Correct, maybe I should leave a note. Thank you. – alex May 31 '10 at 01:06