【问题标题】:How to know when a recursive function has stopped calling itself?如何知道递归函数何时停止调用自己?
【发布时间】:2021-09-26 04:31:44
【问题描述】:

有什么方法可以知道递归函数何时停止调用自己?

我有以下场景:

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 是全局变量(布尔值)。如何知道函数print(msg) 何时不再被调用?换句话说,我怎么知道算法已经停止了?

【问题讨论】:

    标签: javascript algorithm recursion settimeout


    【解决方案1】:

    您可以在开始时一起测试布尔值。如果其中任何一个 === true 则不是finished

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

    【讨论】:

    • 我觉得他不是这个意思。看我的回答。
    • @Ofek - OP 暗示变量是布尔值,一旦满足,它将等于 false。但如果我弄错了,我会让 OP 澄清
    • 你无法知道 canContinueCase2 在最后 2 秒是否为假...
    • 另外,应该是 !(... || canContinueCase3 || (canContinueCase4 && canContinueCase5 && !otherBoolean))
    • 对不起,你把我弄丢了。最后2秒是什么?这里没有场景。此外,您的嵌套条件在本质上与我的没有任何不同 - 所有布尔值都必须为假才能得到满足。真的,在 OP 给出一个实际用例并且我们看到逻辑是如何处理的之前,这都是学术和推测的。
    【解决方案2】:

    你可以使用计数器:

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

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多