1

So I created a count down timer that starts when the person clicks on the button. the countdown timer works but the issue i an running into are two things:

  1. if a person click on the button a second time it speeds up the timers
  2. If a person click on the button after the timer finish it starts to show a negative number.

I am still learning Java and cannot figure this one out.

<button 
style="
background:#f1b005;
margin-bottom: 25px;
border:0px;
color: White;
text-align: center;
text-decoration: none;
display: inline-block;
height:50px;
width:125px;
border-radius: 5px;
align:center;
cursor: pointer;"
onclick="onTimer()">
120 Sec Rest
</button>
<div 
style="60px;
font-size:30px;
text-align:center;
color:#f1b005;"
id="mycounter">
</div>
<script>
i = 120;
function onTimer() {
  document.getElementById('mycounter').innerHTML = i;
  i--;
  if (i < 0) {
    alert('Times Up! Lets Get It!');
    clearInerval(i);
  }
  else {
    setTimeout(onTimer, 1000);
  }
}
</script>

1 Answers1

1

You have multiple mistakes. You wrote clearInerval(i) instead of clearInterval(i). You put the definition of i outside the function - so it's set once, and every time it's clicked, it does the function but does not reset i.

It speeds down because you are doing i--, which makes the value of i one lower.

The major problem is that you set i outside the function. Try this:

<script>
function onTimer() {
  i = 120;
  document.getElementById('mycounter').innerHTML = i;
  i--;
  if (i < 0) {
    alert('Times Up! Lets Get It!');
    clearInterval(i);
  }
  else {
    setTimeout(onTimer, 1000);
  }
}
</script>

Look here for an example of nicer code, just change i++ to i-- to make it count down instead of up in this example: Javascript Second Counter

yes
  • 177
  • 9
  • Thank you. Still learning and this helped a lot. I see my mistakes. I think because i was looking at it for so long i didnt see the errors and got frustrated – Mr. Franklin I May 28 '21 at 17:56
  • It happens. That's how we learn! Debugging is the hardest and most time consuming part of coding :) Consider using an IDE like vscode, it'll help you fix the most glaring errors that are still hard to catch. – yes May 29 '21 at 09:34