完成后如何重新启动函数 - Javascript



主要思想是尽可能快地永远循环函数,如下所示:

function tick(){
    callAnotherFunction(); 
    // waiting for callAnotherFunction() to finish...
    // ...oh it's done -> call tick() again
    /* I tried to call tick(); before and after the closing curly bracket,
    but on the inside it leads to "Maximum call stack size exceeded"-ERROR
    and on the outside it never calls the function again. */
}

你正在做一个递归调用,函数tick()将永远不断地调用自己,永远不会超过这一点,为了做一个递归,你需要定义你的退出条件,只要满足这个条件,递归就会停止,实际执行开始:

var i=0;
function tick(){
callAnotherFunction(); 
waiting for callAnotherFunction() to finish...
...oh it's done -> call tick() again
If(i++ <100) // this our exit condition, recursion stops whenever i => 100
   tick(); 
}

在 jQ 中,你可以使用 when() 和 then()

https://api.jquery.com/jquery.when/

如果没有 jQ,您可以在另一个函数的末尾添加"return 1",然后将此结果放入变量中。然后它会通过一个简单的 if(variable){tick();}

最新更新