How to know when a recursive function has stopped calling itself?

Viewed 59

Is there any way to know when a recursive function has stopped calling itself?

I have the following scenario:

function print(msg){
  console.log(msg);
  
  if(canContinue){
    print("Hi there");
  }

  if(canContinueCase2){
    setTimeout(()=>{
      print("I was late to the party");
    }, 2000);
  }

  if(canContinueCase3){
    print("Cool right?");
  }

  if(canContinueCase4){
    if(canContinueCase5 && !otherBoolean){
      print("Thank you!");
    }
  }
}

canContinue, canContinueCase2, ... otherBoolean are global variables (booleans). How would one know when the function print(msg) is no longer being called? In other words how can I know that the algorithm has stopped?

2 Answers

You can use a counter:

let counter = 0;

function print(msg){
  console.log(msg);
  
  if(canContinue){
    counter++;
    print("Hi there");
  }

  if(canContinueCase2){
    counter++;
    setTimeout(()=>{
      print("I was late to the party");
    }, 2000);
  }

  if(canContinueCase3){
    counter++;
    print("Cool right?");
  }

  if(canContinueCase4){
    if(canContinueCase5 && !otherBoolean){
      counter++;
      print("Thank you!");
    }
  }
  counter--;
}

counter++;
print("hi");

//to check if the function is done, use this:
if (counter == 0) {
  
}

You could test the booleans at the start all together. If any one of them === true it's not finished

function print(msg){
  let finished = !(canContinue || canContinueCase2 || canContinueCase3 || canContinueCase4 || canContinueCase5 || otherBoolean);
  // ...
}
Related