Search code examples
javascripttimersetintervalcountdownclearinterval

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>


Solution

  • 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.