1

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

3
  • Declare downloadTimer and timerstop outside of timer function. Everything an inline listener refers, must be globally accessible. Commented Apr 27, 2021 at 7:41
  • Off topic - setInterval(..., 1000) doesn't fire exactly after 1000 ms. To achieve acurate timing you should consider subtracting two Date.now() results (one stored when the start button is clicked and the second one exectuted at the time of the interval callback). Commented Apr 27, 2021 at 7:41
  • The variable downloadTimer is out of context when you call timerstop(). You will have to declare it globally or pass it in to the second function Commented Apr 27, 2021 at 7:43

1 Answer 1

1

Move downloadTimer outside.

var timeleft = 15;
var downloadTimer;

function timer() {
    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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This should be a comment rather than an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.