-1

I am new to javascript. I am trying to clear my timer value on clcking the"clear" button.I tried to use the variable"sec" from myTimer function, but it is not working. Any suggestions? Help is appreciated.

astroboyee
  • 13
  • 1
  • 1
  • 5

2 Answers2

0
let count = 0
let myTimer;

// set timer
myTimer = setInterval(() => count = count + 1 , 1000)

// clear timer
clearInterval(myTimer)

Show the code of your timer so that I can describe the solution in more detail

demark-pro
  • 174
  • 5
  • Questions like these are asked very frequently on Stack Overflow. As such, it's better to find the initial question and mark this question as a duplicate of that original one. – Heretic Monkey Oct 26 '21 at 18:10
  • Here is my timer code:var sec = 5; var timerID; document.getElementById("b1").onclick =function(){ timerID =setInterval(myTimer,1000); }; function myTimer() { document.getElementById("b1").onclick = function() { myTimer() } document.getElementById('demo').innerHTML = sec + "sec."; sec--; if (sec <= -1) { clearInterval(timerID); document.getElementById("demo").innerHTML="Time's Up!"; } } – astroboyee Nov 19 '21 at 17:06
0

the document.getElementsByTagName gets the button and runs the function when clicked.

let timer;
let increment = 0;

timer = setInterval(() => increment++ , 1000)

//gets the button element and clears timer when clicked
document.getElementsByTagName("button").onclick = function() {
    clearInterval(timer)
}
MXCDR
  • 21
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 26 '21 at 18:26