Your stop button references the
myVar
variable which is storing the reference of the timer which is running, and that variable is initialized when the page loads:
onclick="clearInterval(myVar)"
^^^^^
let myVar = setInterval(myTimer ,1000);
^^^^^
The problem is that when you click the resume button, you're not updating the
myVar
variable with the reference to the
new timer, so clicking the stop button just tries to cancel the
previous timer.
onclick="myVar = setInterval(myTimer, 1000)"
Also, just a footnote, your resume button doesn't check whether the timer is already running so it would be possibly to click that button multiple times and have multiple timers running. Not sure if that's relevant but I thought I'd mention it!
Edit
The
setInterval()
function returns a number value representing the ID of the timer. You can use this logic to keep track of whether a timer is active. If the timer is cancelled you can then set the value of
myVar
to an invalid ID (for example, -1), and then when the resume button is clicked you can check whether the
myVar
value contains the invalid ID -1.
let myVar = setInterval(myTimer, 1000);
function stopTimer()
{
if (myVar !== -1) {
clearInterval(myVar);
myVar = -1;
}
}
function startTimer()
{
if (myVar === -1) {
myVar = setInterval(myTimer, 1000);
}
}