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

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Declare `downloadTimer` and `timerstop` outside of `timer` function. Everything an inline listener refers, must be globally accessible. – Teemu Apr 27 '21 at 07: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). – Bronislav Růžička Apr 27 '21 at 07: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 – Ahmad Apr 27 '21 at 07:43

1 Answers1

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);
}
Dhaval Chaudhary
  • 5,428
  • 2
  • 24
  • 39