问题
Basically what I'm trying to do boils down to
function a() {
// Do stuff that waits for things etc
b(a);
}
function b(f) {
f()
}
function a() { b(a); }; function b(f) { f(); }; a() That will cause a too much recursion error after a while though. Apparently javascript doesn't support tail-recursion so that won't work either. I can't think of any way to use a loop here either since I don't want the code executed immediately. So any way to do this or is it impossible?
Also I apologize if this has been asked before, couldn't find anything that helped.
Edit: Also before anyone asks, no I'm not actually using setTimeout so setIntervall isn't an option.
Edit again: Alright hope this shows what I'm trying to do better. I need to call the same code after waiting for things to complete again without actually putting it in a loop and blocking the program.
回答1:
Because each call to a() returns before the next invocation, there is no recursion going on. The runtime system repeatedly makes individual calls to the function, and there won't ever be more than one call going on at any given time.
Breaking it down:
- Somewhere, your code calls
a()to start the cycle - That call to
a()"does stuff" and then invokessetTimeout() - The system arranges for the timeout, and that call returns immediately
- The original call to
a()completes - 100 milliseconds later, the timer fires and the runtime invokes
a()
The cycle just repeats after that.
edit Maybe I should be more explicit: the word recursion refers to a process wherein a function invokes itself (synchronously) either directly or indirectly. Like:
function fibonacci(n) {
return fibonacci(n - 1) + fibonacci(n - 2);
}
What we have in the code posted in the OP is quite different. There's no call to a() being made from within that function (unless the OP left out some important details). Instead, a reference to the function is being handed over to the system. The call via that reference won't take place until a long, long time after the original call has finished.
来源:https://stackoverflow.com/questions/26567046/avoiding-too-much-recursion-error