0

How can I implement into the TimerBreed function the ability to end the repeated autobreed function

e.g. when whichFrog == "second" make the first and third autoBreed loop end so that only the second autoBreed loop is being carried out.

function autoBreed(x, value1, value2, value3){
    population[x] = population[x] + 1;
    setTimeout(autoBreed, 1000, x, value1, value2, value3);
    document.getElementById(value1.toString()).innerHTML = "+1 PER SECOND";
    document.getElementById(value2.toString()).innerHTML = "<b>" + value3.toString() + "</b> Population: " + population[x];
}
function timerBreed(buttonVar, whichFrog){
    if (whichFrog == "first"){      
        autoBreed(0, "autoParaOne", "valueFrogPopOne", "First");    
    } else if (whichFrog == "second"){  
        autoBreed(1, "autoParaTwo", "valueFrogPopTwo", "Second");       
    } else if (whichFrog == "third"){       
        autoBreed(2, "autoParaThree", "valueFrogPopThree", "Third");        
    }
}
Luke
  • 1
  • 2
  • Pass `whichFrog` to `autoBreed` too, and in that function create a new timeout only in the case when `whichFrog` is "second". – Teemu Feb 15 '20 at 15:04
  • 1
    You will probably want [clearTimeout](https://www.w3schools.com/jsref/met_win_cleartimeout.asp) – Jacob Feb 15 '20 at 15:06
  • 1
    Are you aware of https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout ? `setTimeout()` returns value, that is what you can use. – tevemadar Feb 15 '20 at 15:07
  • 1
    Does this answer your question? [How to stop a setTimeout loop?](https://stackoverflow.com/questions/8443151/how-to-stop-a-settimeout-loop) – Smankusors Feb 15 '20 at 15:09

1 Answers1

0

If you declare the setTimeout id in the outer scope or make it a global variable, you will be able to clear the timer from either of the functions.

let timer;
function autoBreed(x, value1, value2, value3){
    population[x] = population[x] + 1;
    timer = setTimeout(autoBreed, 1000, x, value1, value2, value3);
    document.getElementById(value1.toString()).innerHTML = "+1 PER SECOND";
    document.getElementById(value2.toString()).innerHTML = "<b>" + value3.toString() + "</b> Population: " + population[x];
}

function timerBreed(buttonVar, whichFrog){
    if (whichFrog == "first"){      
        autoBreed(0, "autoParaOne", "valueFrogPopOne", "First");    
    } else if (whichFrog == "second"){  
        //autoBreed(1, "autoParaTwo", "valueFrogPopTwo", "Second");   
        clearTimeout(timer);
    } else if (whichFrog == "third"){       
        autoBreed(2, "autoParaThree", "valueFrogPopThree", "Third");        
    }
}
Addis
  • 2,480
  • 2
  • 13
  • 21