Search code examples
javascriptalgorithmrecursionsettimeout

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


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?


Solution

  • 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) {
      
    }