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);
Related
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>
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>
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>
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;
}
}
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.