This might be a really simple thing to ask but I’ve got a JavaScript countdown timer, but I can’t stop it from counting past 0:00. Instead of stopping at this point, it will continue to -1:59 etc.
I’d also like it to play a beeping sound (which can be found here) when the timer reaches zero.
This is the code I’ve got so far:
JavaScript
x
31
31
1
<div class="stopwatch">
2
<div class="circle">
3
<div class="time" id="timer"></div>
4
</div>
5
</div>
6
7
<script>
8
document.getElementById('timer').innerHTML =
9
02 + ":" + 30;
10
startTimer();
11
12
function startTimer() {
13
var presentTime = document.getElementById('timer').innerHTML;
14
var timeArray = presentTime.split(/[:]+/);
15
var m = timeArray[0];
16
var s = checkSecond((timeArray[1] - 1));
17
if(s==59){m=m-1}
18
19
document.getElementById('timer').innerHTML =
20
m + ":" + s;
21
console.log(m)
22
setTimeout(startTimer, 1000);
23
}
24
25
function checkSecond(sec) {
26
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
27
if (sec < 0) {sec = "59"};
28
return sec;
29
}
30
</script>
31
Any help on this would be appreciated.
Advertisement
Answer
To stop the counter when it reaches zero you have to stop calling the startTimer() function. In the following snippet I have implemented a check to do exactly that.
JavaScript
1
15
15
1
function startTimer() {
2
var presentTime = document.getElementById('timer').innerHTML;
3
var timeArray = presentTime.split(/[:]+/);
4
var m = timeArray[0];
5
var s = checkSecond((timeArray[1] - 1));
6
if(s==59){m=m-1}
7
8
document.getElementById('timer').innerHTML =
9
m + ":" + s;
10
console.log(m)
11
// Check if the time is 0:00
12
if (s == 0 && m == 0) { return };
13
setTimeout(startTimer, 1000);
14
}
15