如何知道递归函数何时停止调用自身?
How to know when a recursive function has stopped calling itself?
有什么方法可以知道递归函数何时停止调用自身?
我有以下场景:
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)
何时不再被调用?换句话说,我怎么知道算法已经停止?
您可以在开始时一起测试布尔值。如果其中任何一个 === true 它不是 finished
function print(msg){
let finished = !(canContinue || canContinueCase2 || canContinueCase3 || canContinueCase4 || canContinueCase5 || otherBoolean);
// ...
}
您可以使用计数器:
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) {
}
有什么方法可以知道递归函数何时停止调用自身?
我有以下场景:
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)
何时不再被调用?换句话说,我怎么知道算法已经停止?
您可以在开始时一起测试布尔值。如果其中任何一个 === true 它不是 finished
function print(msg){
let finished = !(canContinue || canContinueCase2 || canContinueCase3 || canContinueCase4 || canContinueCase5 || otherBoolean);
// ...
}
您可以使用计数器:
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) {
}