-2
let canExit = false;

setTimeout(function() {
  canExit = true;
}, 1000);

function recc() {
  if (canExit) {
    console.log("Bye bye…");
  } else {
    console.log("always else…");
    recc();
  }
}

recc();

I think I get it, let me know if my understanding is wrong!

adiga
  • 34,372
  • 9
  • 61
  • 83
Srikanth Gowda
  • 6,163
  • 7
  • 19
  • 34
  • 1
    Your current code results in a `SyntaxError`, you might want to correct that. There also aren't any `async` functions in there? That term has a very specific meaning – CertainPerformance Nov 14 '19 at 08:37
  • yeah i corrected it, hope setTimout is async!! – Srikanth Gowda Nov 14 '19 at 08:41
  • @SrikanthGowda Functions inside `setTimeout` and `setInterval` calls will only run as soon as all synchronous calls have been completed. Which is why `setInterval(,0)` is used to run a function asynchronously. – nick zoum Nov 14 '19 at 08:43
  • @nickzoum i know that, thats what i am trying to say, a callback function of an async function will not pushed to call stack. – Srikanth Gowda Nov 14 '19 at 08:46

2 Answers2

1

No, but there is a chance if recc() function is asynchronous. so never ever depend on a value in recursive function being changed from a async function.

Srikanth Gowda
  • 6,163
  • 7
  • 19
  • 34
0

Initiating a call to the synchronous function recc with a timer makes no difference to whether recc creates a new, additional, stack frame each time it calls itself recursively.

Synchronous recursion will generally add a new frame to the stack on each recursive call unless both

  1. the recursive call is written to meet the criteria of tail recursion, in that is directly returns the value returned by calling itself, without subjecting the value to additional operations, and
  2. the JavaScript engine being used implements the capability to recognize and optimize tail recursion by not generating a new stack frame.
traktor
  • 17,588
  • 4
  • 32
  • 53