How to avoid javascript countdown timer not to go negative? - javascript

I've got here a countdown, for testing purposes I have it set for 10 seconds, but once It's perfected I'll have it as 30 minutes. Everything runs smoothly until the countdown goes negative, I want it to be negative, but in a proper format and for it to not jump from 0 to -01:00. Math.Floor seemed like a good idea, but with this code it ran with negative numbers right away. Also, once it is negative the format is -00:0-0, I would like -00:00.
How can the format be fixed once it's negative?
Please, refrain from object orientated, our web server is several years out of date.
var seconds = 10;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10)
{
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds > 0) {
seconds--;
if (seconds > 8) {
document.body.style.backgroundColor = "green"; }
else if (seconds == 8) {document.body.style.backgroundColor = "yellow";}
else if (seconds == 3) {document.body.style.backgroundColor = "red";}
}
else{
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
<body onload = "getSeconds()">
<p align ="center">
<span id="countdown" style="color:black; font-size: 20px; font-weight: bold"> </span>
</p>
</body>

Here is a floor function that rounds -0.5 to 0, and -1.5 to -1, as you require:
function floor(x) {
return x | 0;
}
Here is a padding function that correctly pads an integer with 0s:
function pad(n) {
if (n < 0) {
n = -n;
}
if (n < 10) {
return '0' + n.toString();
}
return n.toString();
}
Your code becomes:
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
var seconds = 10;
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 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 == 8) {document.body.style.backgroundColor = "yellow";}
else if (seconds == 3) {document.body.style.backgroundColor = "red";}
}
else{
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
</head>
<body onload = "getSeconds()">
<p align ="center">
<span id="countdown" style="color:black; font-size: 20px; font-weight: bold"> </span>
</p>
</body>
</html>

I think the simplest way is to always treat seconds as positive, but then display a - if it is, in fact, negative:
var abs_seconds = Math.abs(seconds);
var is_negative = seconds < 0;
var minutes = Math.round((abs_seconds - 30)/60);
var remainingSeconds = abs_seconds % 60;
if (remainingSeconds < 10)
{
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = (is_negative ? '-' : '') + minutes + ":" + remainingSeconds;
seconds--;
if (!is_negative) {
if (seconds > 8) {
document.body.style.backgroundColor = "green";
} else if (seconds == 8) {
document.body.style.backgroundColor = "yellow";
} else if (seconds == 3) {
document.body.style.backgroundColor = "red";
}
}
https://jsfiddle.net/sdd8ubxh/2/

For the rounding, I think using parseInt() rather than Math.floor() will get you what you're looking for (truncation).
As for the format, I think you will need to check whether remaining seconds is less than 0:
var isNegative = false;
if(seconds < 0)
{
isNegative = true;
remainingSeconds = Math.abs(remainingSeconds);
}
And then later prepend "-" if isNegative.

Related

Why is my `minutes` number goes into negatives?

I've been working on a timer for a few weeks now. When I try to subtract minutes from 0, it goes into negatives without touching the hours. I've tried a few methods, read the documentation, and watched several YouTube videos, but none of them help me. Here's the code I used:
seconds--;
if (seconds === 0) {
seconds = 59;
minutes--;
if (minutes < 10) {
minutesText.innerText = '0' + minutes.toString()
} else {
minutesText.innerText = minutes;
}
if (minutes === 0) {
minutes = 59;
hours--;
if (hours < 10) {
hoursText.innerText = '0' + hours.toString()
} else {
hoursText.innerText = hours;
}
if (hours === 0) {
window.clearInterval(interval);
}
}
}
if (seconds < 10) {
secondsText.innerText = '0' + seconds.toString();
} else {
secondsText.innerText = seconds;
}
It never touches the hours-- and doesn't make minutes be equal to 59.
(Sorry if it's an easy fix, I'm just getting started on JS)
You have a couple of problems:
You're updating minutesText.innerText before you check whether minutes is 0 and thus needs to be changed to 59. It should be after the if (minutes === 0) block instead.
You need to check if values are 0 before you decrement them, otherwise you will never catch the 0 value.
This snippet incorporates those fixes.
let hoursText = document.getElementById('hours');
let minutesText = document.getElementById('minutes');
let secondsText = document.getElementById('seconds');
function updateTimer() {
hours = +hoursText.innerText;
minutes = +minutesText.innerText;
seconds = +secondsText.innerText;
if (seconds === 0) {
seconds = 59;
if (minutes === 0) {
minutes = 59;
if (hours === 0) {
window.clearInterval(interval);
return;
} else {
hours--;
}
if (hours < 10) {
hoursText.innerText = '0' + hours.toString()
} else {
hoursText.innerText = hours;
}
} else {
minutes--;
}
if (minutes < 10) {
minutesText.innerText = '0' + minutes.toString()
} else {
minutesText.innerText = minutes;
}
} else {
seconds--;
}
if (seconds < 10) {
secondsText.innerText = '0' + seconds.toString();
} else {
secondsText.innerText = seconds;
}
}
interval = setInterval(updateTimer, 1000);
<div><span id="hours">00</span>:<span id="minutes">01</span>:<span id="seconds">13</span></div>

Javascript timer breaking when put in loop

So I am trying to make a timer on Javascript, I'm new so it is very basic. I have it working so that the minutes and the seconds change correctly but when I try to do it in a loop it messes it up. Any help would be great.
var seconds = 5;
var minutes = 3;
function countdown() {
for (i = 0; i < 3; i++) {
if (seconds > 0) {
seconds--;
setTimeout("countdown()", 1000);
} else if (seconds <= 0) {
minutes--;
seconds = 5;
}
}
document.getElementById("timer").innerHTML = minutes + "M " + seconds + "S";
}
countdown();
<p id="timer"></p>
function startCountdown(minutes, seconds) {
updateElement()
var timerId = setInterval(function() {
if(--seconds < 0) {
seconds = 59
--minutes
}
if(minutes <= 0 && seconds <=0 ) {
clearInterval(timerId)
minutes = seconds = 0
}
updateElement()
}, 1000);
function updateElement() {
document.getElementById("timer").innerHTML = minutes + "M " + seconds + "S"
}
}
startCountdown(5, 3)
<p id="timer"></p>

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;
}
}

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);

Countdown HH:MM:SS in Jquery

I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong
Here is code
<div id="timer"></div>
JS
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Here is JsFiddle link CountDown Timer
Well, let's take a look at what your code does:
Set count to the string value 62.
Convert it to HHMMSS, so now count is equal to the string 00:01:02
Start the timer.
On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.
Okay, so with that out of the, way how about fixing it:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
http://jsfiddle.net/5LWgN/17/
If you use the jquery moment plugin. If you are not using jQuery moment then you can use formatTime(seconds) function that is in the #Niet's answer https://stackoverflow.com/a/18506677/3184195
var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
start_time++;
var formate_time = moment.utc(start_time * 1000).format('mm:ss');
$('#Duration').text(formate_time);
}, 1000);
});
function clear() {
if (start_timer) clearInterval(start_timer);
}

Categories

Resources