So I created a website that's going to be a game eventually for a personal project and I've been working on my start and stop button for a countdown timer. My Start button works and counts down perfectly but my stop button doesn't stop my countdown timer like it's supposed to.
This is my javaScript functions for the start and stop buttons for the timer
function countDown(){
var currTime = 55
var timedown = setInterval(function() {
currTime = currTime - 1;
document.getElementById("countdowntimer").innerHTML ="The time is:" + currTime;
if(currTime == 0){
clearInterval(timedown);
document.getElementById("countdowntimer").innerHTML = "BLASTOFF!"
}
else if(currTime < 25){
document.getElementById("countdowntimer").innerHTML = "Half way to launch " + currTime;
} //this is my count down timer function
}, 1000);}
function stopCount() {
for (var i = 0; i < countDown.length; i++) {
clearInterval(countDown[i]);
}
}
//this is supposed to be my stop count function that isn't working
and then this is the part of the HTML file where im calling upon them. My start button works but my stop doesn't
<button id="stopTime" onclick = stopCount() >Stop!</button>//stop Timer button
<button onclick=countDown()>Start Countdown!</button> //Start timer button
I don't know what im doing wrong here but i just can't get it to work
The interval isn't scoped to a place where stopCount() can access it. This is a working example. I've shortened the time for testing.
var timedown
function countDown(){
var currTime = 4
timedown = setInterval(function() {
currTime = currTime - 1;
document.getElementById("countdowntimer").innerHTML ="The time is:" + currTime;
if(currTime == 0){
clearInterval(timedown);
document.getElementById("countdowntimer").innerHTML = "BLASTOFF!"
}
else if(currTime <= 2){
document.getElementById("countdowntimer").innerHTML = "Half way to launch " + currTime;
}
}, 1000);}
function stopCount() {
clearInterval(timedown)
}
<button id="stopTime" onclick ='stopCount()' >Stop!</button>
<button onclick='countDown()'>Start Countdown!</button>
<div id='countdowntimer'>timedown is now scoped globally and is accessable by the stopCount function</div>