Countdown timer in JavaScript not stopping - javascript

I have a timer that counts down from 5:00 minutes, but it does not stop! It just goes into the negative.
HTML
<p>Click the button to begin the quiz. Good Luck!</p>
<button id="start" class="button">Start</button>
<div class="timer">
Timer: <span id="time"> 5:00 </span> minutes
</div>
JavaScript
document.getElementById('time').innerHTML = 05 + ":" + 00;
function startTimer() {
var p_time = document.getElementById('time').innerHTML;
var timeArray = p_time.split(/[:]+/);
var min = timeArray[0];
var sec = checkSecond((timeArray[1]-1));
if(sec==59){min=min-1}
if(min <= 0 && sec == 0) {alert("Time is up!")}
document.getElementById('time').innerHTML = min + ":" + sec;
setTimeout(startTimer, 1000);
}
function checkSecond(seconds) {
if(seconds <10 && seconds >= 0) {seconds ="0" + seconds};
if(seconds <0) {seconds = "59"};
return seconds;
}
CSS
.timer {
color: var(--primary);
font-size: 16px;
font-weight: bold;
margin: 10px;
}
I have the JS saying that when minutes is less than or equal to 0 AND seconds equal 0, then alert "time is up". So I get the popup alert, but once I click "ok" on the popup, the timer keeps counting down into negative.
Also, in the picture, the "5:00" isn't showing up - it only shows one zero.

You have to tell it to stop. E.g. by returning if the time is up. Something like
if(min <= 0 && sec == 0) {return alert("Time is up!")}
// ^ now the next statements won't run
document.getElementById('time').innerHTML = min + ":" + sec;
setTimeout(startTimer, 1000);

you need to remove the timer by using clearTimeout once the timer completes 5 minutes.
check this if stackoverflow snippets isn't working - https://jsfiddle.net/e5v80xmk/
document.getElementById('time').innerHTML = 05 + ":" + 00;
document.getElementById('start').addEventListener('click', startTimer);
var timerRef = null;
function startTimer() {
var p_time = document.getElementById('time').innerHTML;
var timeArray = p_time.split(/[:]+/);
var min = timeArray[0];
var sec = checkSecond((timeArray[1] - 1));
if (sec == 59) {
min = min - 1
}
document.getElementById('time').innerHTML = min + ":" + sec;
if (min <= 0 && sec == 0) {
clearTimeout(timerRef)
alert("Time is up!")
return
}
timerRef = setTimeout(startTimer, 1000);
}
function checkSecond(seconds) {
if (seconds < 10 && seconds >= 0) {
seconds = "0" + seconds
};
if (seconds < 0) {
seconds = "59"
};
return seconds;
}
<p>Click the button to begin the quiz. Good Luck!</p>
<button id="start" class="button">Start</button>
<div class="timer">
Timer: <span id="time"> 5:00 </span> minutes
</div>

Related

timer is not stopped when it reaches zero

I'm trying to build a timer that when it reaches zero it stops. I've tried to make it with a clearInterval but it is not working. As it does nothing.
function startGame() {
var minute = 00;
var sec = 10;
const timeInterval = setInterval(function() {
document.getElementById("gameTimer").innerHTML =
minute + " : " + sec;
sec--;
if (sec == 00) {
minute--;
sec = 59;
if (minute == 00) {
minute = 0;
clearInterval(timeInterval)
}
} else if (minute == 0 && sec == 1) {
document.getElementById("finishGame").innerHTML = "hello"
}
}, 1000);
};
<span id="gameTimer"></span>
<button onClick="startGame()">Start Counter</button>
<span id="finishGame"></span>
You need to use minute <= 0 condition, since you subtract one from minute first, and then check for minute == 0, which will be false, since minute will be -1.
Also, its better to put all if conditions first, then subtract one from second.
function startGame() {
var minute = 0;
var sec = 10;
const timeInterval = setInterval(function() {
document.getElementById("gameTimer").innerHTML = minute + " : " + sec;
if (sec <= 0) {
minute--;
sec = 59;
if (minute <= 0) {
minute = 0;
clearInterval(timeInterval)
}
} else if (minute == 0 && sec == 1) {
document.getElementById("finishGame").innerHTML = "hello";
}
sec--;
}, 1000);
};
<body>
<span id="gameTimer"></span>
<button onClick="startGame()">Start Counter</button>
<span id="finishGame"></span>
</body>

Stopwatch in Javascript is slower than normal time

I want to make a stopwatch in JavaScript that could count milliseconds, seconds and minutes. This is what I have: (you can stop the timer by pressing space)
var counter = document.getElementsByTagName('h1')[0];
var miliseconds = 0;
var seconds = 0;
var minutes = 0;
function Add() {
miliseconds++;
if (miliseconds >= 99) {
miliseconds = 0;
seconds++;
if (seconds >= 59) {
seconds = 0;
minutes++;
}
}
counter.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
(seconds ? (seconds > 9 ? seconds : "0" + seconds) : "00") + ":" +
(miliseconds ? (miliseconds > 9 ? miliseconds : "0" + miliseconds) : "00");
Timer();
}
function Timer() {
t = setTimeout(Add, 10);
}
Timer();
document.addEventListener("keypress", function(e) {
if (e.keyCode === 32) {
clearTimeout(t);
}
});
<h1 id="counter">00:00:00</h1>
The problem is that it seems to not go at the proper speed, meaning that when I compare it to other timers, it gradually becomes slower than them (i.e the speed at which the timer is counting slows down over time). So suddenly, there are 5-second differences, then it becomes 7-second differences and so on.
Any help would be appreciated.
You should create a startTime variable, then calculate the elapsedTime, and use that to calculate additional variable to show.
var startTime = Date.now();
setTimeout(function(){
var elapsedTime = Date.now() - startTime;
// Additional code to calculate hour, minute, second, milisecond here
}, 10);

How do I script a function to add seconds to a JavaScript count up timer displaying in HTML?

I found a sample JavaScript count up timer that meets my needs, including a start/pause and reset function. However it's missing one thing that I need it to do; have the script add 2 seconds to the display timer when a button is selected.
Here is my HTML:
<!doctype html>
<html>
<head>
<title></title>
</head>
<p><span id="my_timer" style="color: #f00; font-size: 2000%; font-weight: bold;">00:00:00</span></p>
<button id="control" onclick="changeState();">START</button>
<button id="reset" onClick="reset();">RESET</button>
<button id="updateClock" onClick="updateClock();">2 SECONDS</button>
<script type="text/javascript" src="timer.js"></script>
<body>
</body>
</html>
And here is my JavaScript:
// boolean keeps track of timer state
var active = false;
//main function
function start_timer() {
//function active if true
if (active) {
var timer = document.getElementById("my_timer").innerHTML;
var arr = timer.split(":"); //spliting timer into array by ':', so hour goes to arr[0], minutes go to arr[1], etc.
var hour = arr[0]; //getting hour
var min = arr[1]; //minutes
var sec = arr[2]; //seconds
if (sec == 59) {
if (min == 59) {
hour++;
min = 0;
if (hour < 10) hour ="0" + hour;
} else {
min++;
}
if (min < 10) min = "0" + min;
sec = 0;
} else {
sec ++;
if (sec < 10) sec = "0" + sec;
}
//update our html
document.getElementById("my_timer").innerHTML = hour + ":" + min + ":" + sec;
setTimeout(start_timer, 1000); //repeat with speed of 1 second
}
}
//functions to change states - start or pause timer by clicking
function changeState () {
if (active == false) {
active = true;
start_timer();
console.log("Timer has been started");
document.getElementById("control").innerHTML = "PAUSE";
} else {
active = false;
console.log("Timer is on pause");
document.getElementById("control").innerHTML = "START";
}
}
//reset function
function reset() {
document.getElementById("my_timer").innerHTML = "00" + ":" + "00" + ":" + "00";
console.log("Timer has been reset");
}
How would I script a function that would add 2 seconds to the display timer?
Below only works while the timer is running. To get the button to add two seconds whether the timer is running or not, remove the 'if (active){'.
// add two seconds to displayed time
function start_timer(){
if (active) {
var timer = document.getElementById("my_timer").innerHTML;
var arr = timer.split(":"); //spliting timer into array by ':', so hour goes to arr[0], minutes go to arr[1], etc.
var hour = arr[0]; //getting hour
var min = arr[1]; //minutes
var sec = arr[2]; //seconds
if ((sec == 58) || (sec == 59)) {
if (min == 59) {
hour++;
min = 0;
if (hour < 10) hour ="0" + hour;
} else {
min++;
}
if (min < 10) min = "0" + min;
if (sec == 58){
sec = 0;
}
if (sec == 59){
sec = 1;
}
} else {
sec = parseInt(sec) + 2;
if (sec < 10) sec = "0" + sec;
}
//update our html
document.getElementById("my_timer").innerHTML = hour + ":" + min + ":" + sec;
}
}

How do you decrement time for minutes seconds hundredths?

Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
Three issues appear to need attention.
"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>

Display minutes and seconds total in Javascript Timer

Everything I have so far is working great, although I'd like an alert that will display the amount of time used on the timer.
Example, starting timer at 00:10 and stopping at -00:20, the message alert should say 30 seconds
My problem is stopTimer() which is the STOP button, on click it should display the amount of seconds, minutes however I'm having trouble with.
How can I form minutes in there as well, if the client went that long? JsFiddle
var totseconds = 10;
var seconds = totseconds;
function floor(x) {
return x | 0;
}
function pad(n) {
if (n < 0) {
n = -n;
}
if (n < 10) {
return '0' + n.toString();
}
return n.toString();
}
function stopTimer() {
clearTimeout(countdownTimer);
if (seconds > 60) {
var rs = seconds % 60;
var m = seconds / 60;
windows.alert((totalseconds / 60) - (m + 1) + " minutes and " + totalseconds - (rs + 1) + " seconds")
}
//else {window.alert((seconds +1)+ " seconds");}
else {
window.alert(totseconds - (seconds + 1) + " seconds");
}
}
function secondPassed() {
var minutes = pad(floor(seconds / 60));
if (seconds < 0) {
minutes = '-' + minutes;
}
var remainingSeconds = pad(seconds % 60);
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds > 0) {
seconds--;
if (seconds > 8) {
document.body.style.backgroundColor = "green";
} else if (seconds == 5) {
document.body.style.backgroundColor = "yellow";
}
} else {
document.body.style.backgroundColor = "red";
if (seconds % 2 == 0) {
document.getElementById('skull').style.display = "block";
}
if (seconds % 2 != 0) {
document.getElementById('skull').style.display = "none";
}
seconds--;
}
}
<img id="skull" src="http://s15.postimg.org/es5w3xpob/skull.gif" style="position:absolute; z-index: -1;display:none;">
<div style=" z-index:10;">
<p align="center"> <span id="countdown" style="color:black; font-size: 50px; font-weight: bold;"></span>
</br>
<button onclick="countdownTimer = setInterval('secondPassed()', 1000)">Start</button>
<button onclick="stopTimer()">Stop</button>
</p>
</div>
Confusion caused by counting seconds backwards seems to be the problem. On the fiddle in function stopTimer() changing
if (seconds > 60) { // .... more than a minute
to
if(seconds < -60) { // ... more than a minute
causes code for over a minute to get executed (which as written has errors and will need debugging). To clarify the logic and make coding easier when counting backwards may I suggest calculating something like
var elapsedSeconds = - (seconds - totseconds);

Categories

Resources