I want to implement a basic timer program that starts a 15 second timer on start button and stops on stop button
Here is what I have done so far
JS
var timeleft = 15;
function timer(){
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
function timerstop(){
clearInterval(downloadTimer);
}
}
HTML
<div id="countdown"></div>
<button onclick="timer();">start</button>
<button onclick="timerstop();">stop</button>
The reason I had to use the nested function approach was to access the variable downloadtimer, the start button works as expected but on clicking the stop button I get the following error
Uncaught ReferenceError: timerstop is not defined
I would like to know if is this is a programming error or should I change my approach
Thanks in Advance
downloadTimerandtimerstopoutside oftimerfunction. Everything an inline listener refers, must be globally accessible.setInterval(..., 1000)doesn't fire exactly after 1000 ms. To achieve acurate timing you should consider subtracting twoDate.now()results (one stored when the start button is clicked and the second one exectuted at the time of the interval callback).downloadTimeris out of context when you calltimerstop(). You will have to declare it globally or pass it in to the second function