Skip to content Skip to sidebar Skip to footer

Avoiding 'too Much Recursion' Error

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)

Solution 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 invokes setTimeout()
  • 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.

Post a Comment for "Avoiding 'too Much Recursion' Error"