开发者

javascript - how to restart a function from inside it?

How do I restart a fu开发者_JAVA技巧nction calling it from inside the same function?


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();


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();
)();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜