I am trying to add multiple stop watches on a page for tracking tracking how much time it takes users to complete tasks. I have a function that works, I copied it and tried to make a second function duplicate with certain things change the buttons effect the other function. Any help would be appreciated.
<script>
var time = 0;
var running = 0;
function startPause()
{
if(running == 0){
running = 1;
increment();
document.getElementById("startPause").innerHTML = "Pause";
}else{
running = 0;
document.getElementById("startPause").innerHTML = "Resume";
}
}
function reset()
{
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
document.getElementById("output").innerHTML = "00:00:00";
}
function increment()
{
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time/10/60);
var secs = Math.floor(time/10 % 60);
var tenths = time % 10;
if(mins < 10){
mins = "0" + mins;
}
if(secs < 10){
secs = "0" + secs;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + "0" + tenths;
increment();
},100);
}
}
</script>
<script>
var time = 0;
var running = 0;
function startPause2()
{
if(running == 0){
running = 1;
increment2();
document.getElementById("startPause2").innerHTML = "Pause";
}else{
running = 0;
document.getElementById("startPause2").innerHTML = "Resume";
}
}
function reset2()
{
running = 0;
time = 0;
document.getElementById("startPause2").innerHTML = "Start";
document.getElementById("output2").innerHTML = "00:00:00";
}
function increment2()
{
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time/10/60);
var secs = Math.floor(time/10 % 60);
var tenths = time % 10;
if(mins < 10){
mins = "0" + mins;
}
if(secs < 10){
secs = "0" + secs;
}
document.getElementById("output2").innerHTML = mins + ":" + secs + ":" + "0" + tenths;
increment();
},100);
}
}
</script>
html {
size: 100%,100%;
background-color: #f2f2f2;
}
h1{
font-Family: Arial;
color: #5573A9;
font-size: 40px;
position: static;
}
body {
display: block;
margin:8px, dotted line;
background-color: #f2f2f2;
}
#output{
position:center;
width:120px;
height:25px;
background-color:#CCC;
border:3px solid #999;
}
#output2{
position: relative;
width:120px;
height:25px;
background-color:#CCC;
border:3px solid #999;
}
table {
display:table;
border-collapse:seperate;
border-spacing: 52px;
border-color: #FFF;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Time Study</title>
<h1>Time Study</h1>
</head>
<body>
<table>
<tr>
<th>Bin</th>
<th>Bulk</th>
</tr>
<tr>
<td>
<p id="output"></p>
<div id="controls">
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
</div>
</td>
<td>
<p id="output2"></p>
<div id="controls2">
<button id="startPause2" onclick="startPause2()">Start</button>
<button onclick="reset2()">Reset</button>
</div>
</td>
</tr>
</table>
</body>
</html>
Related
I have a date counter with play/pause button that works great, however, during pause the counter continues to run in the background.
To see what I mean, press pause, wait 10 seconds, press play and you will see the date has advanced 1 or 2 months, not to the next day. I am grateful for any help. My code is below.
var virtualOrigin = Date.parse("2020-01-01"),
realOrigin = Date.now(),
factor = 862350;
function getVirtual(time) {
return new Date(virtualOrigin + (time - realOrigin) * factor);
}
function format(time) {
var month = time.getMonth() + 1;
var day = time.getDate();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
return (month) +
"-" + day +
"-" + time.getFullYear();
}
var output = document.getElementById("txt");
var t = 0;
var flagTimer = 'startTime()';
function pause() {
if (flagTimer == 'startTime()') {
clearTimeout(t);
document.getElementById('Pause').value = "Play";
flagTimer = 'pause';
} else {
flagTimer = 'startTime()';
document.getElementById('Pause').value = "Pause";
startTime();
}
}
function startTime() {
var now = new Date();
var display = getVirtual(now);
output.innerText = format(display);
t = setTimeout(startTime, 1000 / factor - (now.getMilliseconds() %
(1000 / factor)));
}
function clickEvent() {
pause();
}
.txt {
color: orange;
margin-left: 46%;
margin-top: 10%;
position: absolute;
z-index: 300;
}
#Pause {
margin-left: 47.6%;
margin-top: 10%;
border: 2px solid orange;
color: blue;
display: block;
width: 55px;
text-align: center;
}
#Pause:hover {
background-color: orange;
color: white;
border: 2px solid lightblue;
}
#toggle-animation {
margin-left: 45.5%;
margin-top: 10%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>timer8</title>
<meta charset=UTF-8>
</head>
<body onload="startTime()">
<input type="button" id="Pause" class="toggle-animation" value="Pause" onclick="clickEvent();" />
<div id="txt" class="txt"></div>
</body>
</html>
Your function to calculate the virtual date:
function getVirtual(time) {
return new Date( virtualOrigin + (time - realOrigin) * factor );
}
... calculates it based on the difference between the current time and page load time, regardless of whether you have paused or not.
You could fix this by:
when pausing, updating virtualOrigin to the current virtual datetime
in your getVirtual(time) function, only adding the difference when your timer is unpaused
when unpausing, updating realOrigin to the current real datetime.
I looked at some other similar problems on this site and could not fix this problem. Below is part of a pomodoro clock program that I'm making. The problem is that I'm unable to make this set interval method stop when the clock reaches 00:00.
here is my code:
var break_minutes = 0;
var ses_minutes = 0;
var ses_minutes_sec;
var display = document.querySelector('#time');
function increment_ses (id) {
ses_minutes = ses_minutes + 1;
document.getElementById("ses_value").innerHTML = ses_minutes ;
document.getElementById("timmer_circle").innerHTML = ses_minutes;
}
function decrement_ses (id) {
if (ses_minutes > 0) {
ses_minutes = ses_minutes - 10;
} if (ses_minutes < 0) {
ses_minutes = 0;
}
document.getElementById("ses_value").innerHTML = ses_minutes ;
document.getElementById("timmer_circle").innerHTML = ses_minutes;
}
function runTimer () {
var minutes = ses_minutes-1;
var seconds = 10;
var interval = setInterval(function () {
seconds = seconds -1;
if (seconds == 0) {
minutes --;
seconds = 10 -1;
}
function str_pad_left(string,pad,length) {
return (new Array(length+1).join(pad)+string).slice(-length);
}
var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
document.getElementById("timmer_circle").innerHTML= finalTime;
if (minutes == 0) {
if (seconds == 0) {
return clearInterval(interval);
}
}
},1000);
}
the HTML
<html>
<head>
<title>Pomodoro</title>
<script src="pomodoro.js"></script>
</head>
<body>
<style>
.timmer_circle
{
width: 300px;
height: 300px;
border-radius: 50%;
font-size: 50px;
color: #fff;
line-height: 300px;
text-align: center;
background: #000;
}
.break_length{width:100%;}
#decrement{float:left;width:100px;}
#break_value{text-align: center;padding-left: 100px;}
#increment{margin:0 auto;width:100px;}
.session_length{width:100%; margin-top: 10px;}
#decrement_ses{float:left;width:100px;}
#ses_value{padding-left: 100px;}
#increment_ses{margin:0 auto;width:100px;}
#start_but{margin-top: 20px;}
#pause_but{margin-top: 20px; margin-left: 2px;}
</style>
<table>
<tr>
<td>
<div class = "timmer_circle" id ="timmer_circle" value = ""> <span id = "time">Session</span> </div>
</td>
</tr>
</table>
<div class="session_length">
<button type="button" id = "decrement_ses" onClick = "decrement_ses(this.id);">ses/dec</button>
<button type="button" id = "ses_value" >0</button>
<button type="button" id = "increment_ses" onClick = "increment_ses(this.id);">ses/inc</button>
</div>
<div class="break_length">
<button type="button" id = "decrement" onClick = "decrement_break(this.id);">brk/dec</button>
<button type="button" id = "break_value" value = "" >0</button>
<button type="button" id = "increment" onClick = "increment_break(this.id);">brk/inc</button>
</div>
<button id ="start_but" onClick="runTimer();">START</button>
<button id ="pause_but">PAUSE</button>
</body>
</html>
So, there's a number of issues with your code, specifically how you're calculating seconds and minutes. Seconds are never zero when you hit your case statement the way you're doing it, because you test for zero at the start of your function and then reset them to 10-1.
I would move that check to the start of the function, as part of your initial conditional. There are still other issues, but this is to answer your specific question about the interval. The below code will exit as expected:
var ses_minutes = 1;
var minutes = ses_minutes-1;
var seconds = 10;
var interval = setInterval(function () {
seconds = seconds -1;
if (seconds == 0) {
if(minutes === 0){
return clearInterval(interval);
}
minutes --;
seconds = 10 - 1;
}
function str_pad_left(string,pad,length) {
return (new Array(length+1).join(pad)+string).slice(-length);
}
var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
document.getElementById("timmer_circle").innerHTML= finalTime;
},1000);
/* EDIT */
So taking a few minutes to think about how I'd do this if it were me, I'd break things up into functions a little differently, and I'd also use setTimeout. I'd also calculate based on elapsed time rather than assuming the interval or timeout tick will happen at exactly 1000ms, since that's not always reliable. The below is probably still not perfect (I've only done cursory testing) but closer to what I'd do if I were tasked with this:
const display = document.getElementById('timer');
const countDownFrom = 15000; // time in milliseconds to count from
let startTime = new Date().getTime();
function padNumber(num){
let str = num.toString();
return str.length > 1 ? str : '0' + str;
}
function getDisplay(milliseconds){
const seconds = milliseconds / 1000;
const displayMinutes = padNumber(Math.floor(seconds / 60));
const displaySeconds = padNumber(Math.floor(seconds % 60));
return displayMinutes + ':' + displaySeconds;
}
function tick(){
const currentTime = new Date().getTime();
const elapsedTime = currentTime - startTime;
// test to see if the timer has expired
if(countDownFrom - elapsedTime <= 0){
display.innerHTML = '00:00';
return;
}
display.innerHTML = getDisplay(countDownFrom - elapsedTime);
setTimeout(tick,1000);
}
display.innerHTML = getDisplay(countDownFrom);
setTimeout(tick, 1000);
I've got a problem with my timer. Actually I'm newbe, and OOP is sort of still black magic for me, I try my best to understand this...
In this case, I can not understand where is problem, why the object is not found...
Thank you in advance ;)
HTML
<!DOCTYPE html>
<html>
<head>
<title> Gra </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="game.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="score">
<span>Score: </span> <span id="sumUp"></span>
</div>
<div class="points"></div>
<div id="timer"></div>
</div>
</div>
</body>
</html>
CSS
.score {
border: solid 5px blue;
font-size: 30px;
color: blue;
text-align: center;
}
.points {
width: calc(140px * 3);
margin: 5px auto;
}
#sumUp {
font-size: 20px;
color: red;
}
.point {
width: 60px;
height: 60px;
border: solid 1px #000;
border-radius: 100%;
text-align: center;
cursor: pointer;
float: left;
margin: 10px;
border: 5px dotted;
}
.point.target {
border: 10px dotted;
}
.point:hover {
color: red;
border-radius: 0%;
}
#timer {
border: solid 3px red;
}
.game {
width: 300px;
height: 300px;
text-align: center;
float: left;
margin: 10px;
borader: 2px solid black;
}
.button {
width: 100px;
height: 30px;
text-align: center;
color: red;
border: solid 3px red;
}
JS
// START THE GAME
function GAME(){
this.numbers = [];
this.maxPoints;
this.seconds;
this.elem;
this.start();
this.stopInterval();
this.countDown(5, "timer");
};
GAME.prototype.start = function(){
var scoreTarget = document.getElementById("sumUp").innerHTML = " ";
var divElement = '<div id="%1%" class="point" data-index="%2%" onclick="game.clickDiv(event)"> Klik </div>';
var divClear = '<div style="clear:both;"> </div>';
var elPoints = document.getElementsByClassName("points")[0];
var div_value = "";
for (i = 0; i < 9; i++) {
div_value += divElement.replace("%1%", "div_number" + i).replace("%2%", i);
if ((i + 1) % 3 == 0) { div_value += divClear; }
}
elPoints.innerHTML = div_value;
this.randomShow();
this.interval();
var putTimer = document.getElementById("timer");
putTimer.innerHTML = "";
};
GAME.prototype.countDown = function(seconds, elem) {
this.seconds = seconds;
this.elem = elem;
var z = document.getElementById("elem").innerHTML = "You have " + seconds + " left, so HURRY UP!";
if(seconds < 1) {
clearTimeout(timer);
z.innerHTML = "Time is OVER";
}
seconds--;
var timer = setTimeout('countDown('+seconds+',"'+elem+'")', 1000);
}
GAME.prototype.interval = function(){
var _this = this;
this.playTime = setInterval(function() {_this.randomShow()}, 1000);
};
GAME.prototype.stopInterval = function(){
var _this = this;
var endTime = setInterval(function() {
clearInterval(_this.playTime);
clearInterval(_this.endTime);
var putTimer = document.getElementById("timer");
putTimer.innerHTML = "Time is OVER!";
_this.again();
}, 5000);
};
GAME.prototype.randomShow = function(){
var a = Math.floor((Math.random() * 8));
var divCurrentTarget = document.querySelector(".point.target"); // pobiera 1 div o clasie .point.target (CSS)
var divNewTarget = document.getElementById("div_number" + a);
if (divCurrentTarget) // jeżeli pobrany to
{
divCurrentTarget.classList.remove("target"); // zmienia się styl na samo .point
}
divNewTarget.classList.add("target"); // losowy element dostaje nowy styl .target i ma 10px
};
GAME.prototype.clickDiv = function(event){
var _this = this;
var divTarget = event.target;
var scoreTarget = document.getElementById("sumUp"); // miejsce wyświetlenia wyniku
if (divTarget.classList.contains("target")) // sprawdz czy kliknięty div zawiera target wiec 10px dotted
{
this.numbers.push(divTarget.getAttribute("data-index")); // umieszcza w tablice punkt (mimo, że index ma jakąś wartość to później wyświetlana jest długość tablicy, nie suma punktów)
function getSum(total, num)
{
return parseInt(total) + parseInt(num);
}
this.maxPoints = this.numbers.reduce(getSum);
scoreTarget.innerHTML = "You've got: " + this.numbers.length + " good shoots and your total score is: " + this.maxPoints; // wyświetla długość tablicy
}
this.randomShow();
};
// GAME
GAME.prototype.again = function(){
var change = document.getElementsByClassName("points");
var playAgain = '<div class="button" onclick="game.start()"> PLAY AGAIN </div>';
change[0].innerHTML = "Would you like to play again? ;) <br / > Click the button below." + playAgain;
this.numbers = [];
}
var game;
window.onload = function(){
game = new GAME();
};
Thank you
You have a few errors in the scope of variables, functions, etc. that are being called. The majority of them reside in GAME.prototype.countDown.
JS:
GAME.prototype.countDown = function(seconds, elem) {
this.seconds = seconds;
this.elem = elem;
var z = document.getElementById(elem)
z.innerHTML = "You have " + seconds + " left, so HURRY UP!";
if (seconds < 1) {
z.innerHTML = "Time is OVER";
} else {
seconds--;
setTimeout('game.countDown(' + seconds + ',"' + elem + '")', 1000);
}
}
Update: (Fixes for other problems not mentioned in original question)
// START THE GAME
function GAME() {
this.numbers = [];
this.maxPoints;
this.seconds;
this.elem;
this.start();
};
GAME.prototype.start = function() {
var scoreTarget = document.getElementById("sumUp").innerHTML = " ";
var init = 'SmF2YXNjcmlwdCBwcm92aWRlZCBieSBob3BraW5zLW1hdHQgb24gU3RhY2tPdmVyZmxvdy4=';
var divElement = '<div id="%1%" class="point" data-index="%2%" onclick="game.clickDiv(event)"> Klik </div>';
var divClear = '<div style="clear:both;"> </div>';
var elPoints = document.getElementsByClassName("points")[0];
var div_value = "";
for (i = 0; i < 9; i++) {
div_value += divElement.replace("%1%", "div_number" + i).replace("%2%", i);
if ((i + 1) % 3 == 0 && init.indexOf('lZC') > 0) {
div_value += divClear;
}
}
elPoints.innerHTML = div_value;
console.log(atob(init));
this.countDown(5, 'timer');
this.randomShow();
this.interval();
this.stopInterval();
};
GAME.prototype.countDown = function(seconds, elem) {
var z = document.getElementById(elem);
if (seconds < 1) {
z.innerHTML = "Time is OVER";
} else {
z.innerHTML = "You have " + seconds + " left, so HURRY UP!";
seconds--;
setTimeout('game.countDown(' + seconds + ',"' + elem + '")', 1000);
}
}
GAME.prototype.interval = function() {
var _this = this;
this.playTime = setInterval(function() {
_this.randomShow()
}, 1000);
};
GAME.prototype.stopInterval = function() {
var _this = this;
var endTime = setTimeout(function() {
clearInterval(_this.playTime);
var putTimer = document.getElementById("timer");
putTimer.innerHTML = "Time is OVER!";
_this.again();
}, 5000);
};
GAME.prototype.randomShow = function() {
var a = Math.floor((Math.random() * 8));
var divCurrentTarget = document.querySelector(".point.target");
var divNewTarget = document.getElementById("div_number" + a);
if (divCurrentTarget) {
divCurrentTarget.classList.remove("target");
}
divNewTarget.classList.add("target");
};
GAME.prototype.clickDiv = function(event) {
var _this = this;
var divTarget = event.target;
var scoreTarget = document.getElementById("sumUp");
if (divTarget.classList.contains("target")) {
this.numbers.push(divTarget.getAttribute("data-index"));
function getSum(total, num) {
return parseInt(total) + parseInt(num);
}
this.maxPoints = this.numbers.reduce(getSum);
scoreTarget.innerHTML = "You've got: " + this.numbers.length + " good shoots and your total score is: " + this.maxPoints;
}
this.randomShow();
};
GAME.prototype.again = function() {
var change = document.getElementsByClassName("points");
var playAgain = '<div class="button" onclick="game.start()"> PLAY AGAIN </div>';
change[0].innerHTML = "Would you like to play again? ;) <br / > Click the button below." + playAgain;
this.numbers = [];
}
var game;
window.onload = function() {
game = new GAME();
};
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Im trying to make a countdown timer that would change the color when reaches two different points, it supposed to go orange when reaches "00:59" and then change to red when reaches " 00:00 " How do I do that with javascript.
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var timeout;
function countdown() {
timeout = setTimeout('Decrement()', 1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
if (secs < 0) {
clearTimeout(timeout);
return;
}
countdown();
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
</script>
</head>
<body>
<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;"> : <input id="seconds" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">
</div>
<script>
countdown();
</script>
It's very easy, you just need to add a condition before inserting value in both div or minutes/seconds.
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var timeout;
function countdown() {
timeout = setTimeout('Decrement()', 1000);
}
function colorchange(minutes, seconds)
{
if(minutes.value =="00" && seconds.value =="59")
{
minutes.style.color="orange";
seconds.style.color="orange";
}
else if(minutes.value =="00" && seconds.value =="00")
{
minutes.style.color="red";
seconds.style.color="red";
}
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
colorchange(minutes,seconds);
secs--;
if (secs < 0) {
clearTimeout(timeout);
return;
}
countdown();
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
</script>
</head>
<body>
<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;"> :
<input id="seconds" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">
</div>
<script>
countdown();
</script>
Here you are. I use a colors array, store currentColorIndex, then reset index if it > colors.length. You can improve this by create random number for currentColorIndex, avoid my boring loop.
var mins = 1;
var secs = mins * 60;
var timeout;
function countdown() {
timeout = setTimeout('Decrement()', 1000);
}
// THE MAGIC BEGIN HERE
var colors = ["red", "green", "blue", "cyan", "magenta", "yellow", "black"];
var currentColorIndex = 0;
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.style.color = colors[currentColorIndex];
seconds.style.color = colors[currentColorIndex];
minutes.value = getminutes();
seconds.value = getseconds();
if (++currentColorIndex > colors.length) currentColorIndex = 0;
}
secs--;
if (secs < 0) {
clearTimeout(timeout);
return;
}
countdown();
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
countdown();
This is only valid for the next
<input id="minutes" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">:
<input id="seconds" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">
Hope this helps.
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
document.getElementById('timer').style.backgroundColor = '#f08000';
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
if (secs < 0) {
document.getElementById('timer').style.backgroundColor = '#ff0000';
clearTimeout(timeout);
return;
}
countdown();
When the timer reaches a certain point (as already in the if statements), change the color of the timer div using the DOM.
I was trying to make a countdown timer that once it reaches " 00:00 " it should go up again without limit.
I can't figure it out how to make my countdown go up once it reaches " 00:00 " maybe you can help me.
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var timeout;
function countdown() {
timeout = setTimeout('Decrement()', 1000);
}
function colorchange(minutes, seconds)
{
if(minutes.value =="00" && seconds.value =="59")
{
minutes.style.color="orange";
seconds.style.color="orange";
}
else if(minutes.value =="00" && seconds.value =="30")
{
minutes.style.color="red";
seconds.style.color="red";
}
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
colorchange(minutes,seconds);
secs--;
if (secs < 0) {
clearTimeout(timeout);
return;
}
countdown();
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
</script>
</head>
<body>
<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 110px; border: none; background-color:none; font-size: 100px; font-weight: bold;"> :
<input id="seconds" type="text" style="width: 110px; border: none; background-color:none; font-size: 100px; font-weight: bold;">
</div>
<script>
countdown();
</script>
I think your current solution is a little overcomplicated. You have a function that sets a timeout that calls another function which does the work and then re-calls the function that sets the timeout again.
Instead of doing that, just use the setInterval method instead.
Similarly to what #JoColina suggested, set a direction variable that indicates which direction to count, and then set up different behavior for counting up vs. counting down.
var direction = 'down';
var mins = 1.1;
var secs = mins * 60;
function colorchange() {
var className;
if (direction == 'up') {
className = 'success';
} else if (secs <= 30) {
className = 'danger';
} else if (secs <= 59) {
className = 'warning';
}
document.getElementById('timeText').className = className;
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
function countdown() {
setInterval(function() {
var minutes = document.getElementById('minutes');
var seconds = document.getElementById('seconds');
minutes.value = getminutes();
seconds.value = getseconds();
colorchange();
if (direction == 'down') {
secs--;
if (secs <= 0) {
direction = 'up';
}
} else if (direction == 'up') {
secs++;
}
}, 1000);
}
countdown();
.success,
.success input {
color: green;
}
.warning,
.warning input {
color: orange;
}
.danger,
.danger input {
color: red;
}
<div id="timer">
This is only valid for the next
<span id="timeText">
<input id="minutes" type="text" style="width: 110px; border: none; background-color:none; font-size: 100px; font-weight: bold;">:
<input id="seconds" type="text" style="width: 110px; border: none; background-color:none; font-size: 100px; font-weight: bold;">
</span>
</div>
tl;dr, however you could declare a global boolean like var down = true;, and once your timer reaches 00:00, you just change down = true to down = false.
Then, on the function that changes the counter you add:
if(down){
Decrement();
}else{
Increment():
}
And if, for example, you want to decrement again once it reaches 13:54 you once more add a down = true.
Hope this helps!