alr500
alr500

Reputation: 15

clearInterval button not stopping setInterval countdown

The idea is to make a simple js countdown with minutes and seconds, showing the numbers in a html doc, with a button to start/continue and another to stop/pause. I got stuck on seconds at pausing the time...The Start button works, but I can't seem to figure out why Stop doesn't work. I've read multiple similar questions trying fixes but still same result. Any ideas?

Many thanks!

var min = 5;
var sec = 60;
var secoutput;
 
document.getElementById("min").innerHTML = min;
if (sec >= 60)
	{document.getElementById("sec").innerHTML = "00";}
else
	{document.getElementById("sec").innerHTML = secoutput; }
   
function start(){
var secoutput = setInterval(function(){
	sec-=1;
    document.getElementById("sec").textContent = sec;
    if(sec <= 0)
        clearInterval (secoutput);
    },1000);
}

function stop(){
        clearInterval (secoutput);
}
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
    
<p id="min"></p>
<p id="sec"></p>

Upvotes: 1

Views: 422

Answers (3)

cathryngriffiths
cathryngriffiths

Reputation: 237

The problem lies in your start() function, where you've re-declared the secoutput variable. Just change this:

var secoutput = setInterval(function(){ ... }

to this:

secoutput = setInterval(function(){ ... }

Upvotes: 0

Evans
Evans

Reputation: 651

The problem is you declare var secoutput = setInterval(function(){ inside of the start() function. Because of this the declaration you can not access that specific variable outside of your start() function. if you simply remove the var declaration and only have a secoutput = setInterval(function(){ then your code will work. You can learn more about closures in JavaScript here.

Upvotes: 1

RustyDev
RustyDev

Reputation: 1122

var min = 5;
var sec = 60;
var secoutput;
 
document.getElementById("min").innerHTML = min;
if (sec >= 60)
	{document.getElementById("sec").innerHTML = "00";}
else
	{document.getElementById("sec").innerHTML = secoutput; }
   
function start(){
    // Removed the var so the original variable is used
    secoutput = setInterval(function(){
	sec-=1;
    document.getElementById("sec").textContent = sec;
    if(sec <= 0)
        clearInterval (secoutput);
    },1000);
}

function stop(){
        clearInterval (secoutput);
}
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
    
<p id="min"></p>
<p id="sec"></p>

Upvotes: 0

Related Questions