Reset first countdown after the second countdown - javascript

Im working on a simple countdown that displays a modal when it is zero, then on that modal there is another countdown, it will close when on zero.
what I want is reset the first countdown again and do the same process.
How can I achieve that?
hope you understand me.
Thanks.
SAMPLE CODE
//declare start time
var timer2 = "00 : 00 : 10";
// timer2 = timer2.replace(/秒|_/g,'')
//intercal for seconds
var interval = setInterval(function() {
//timer will be [hour, minute, second]
var timer = timer2.split(':');
var hour = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
//reduce second by one
--seconds;
//calculate new minute and hours
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
minutes = 00;
seconds = 00;
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function(){
timeleft--;
$('.sec').text(timeleft);
if(timeleft == 0){
clearInterval(downloadTimer);
$('#informationModal').fadeOut();
minutes = 00;
seconds = 10;
}
},1000);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hour = (hour < 0) ? 59 : hour;
hour = (hour < 10) ? '0' + hour : hour;
timer2 = hour + ':' + minutes + ':' + seconds;
$('#countdown').html(timer2);
}, 1000);

Easiest way would be to wrap everything into a function, and call that function again when fadeOut of modal completes.
$('#informationModal').fadeOut(400, startTimer);
function startTimer() {
//declare start time
var timer2 = "00 : 00 : 10";
// timer2 = timer2.replace(/秒|_/g,'')
//intercal for seconds
var interval = setInterval(function() {
//timer will be [hour, minute, second]
var timer = timer2.split(':');
var hour = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
//reduce second by one
--seconds;
//calculate new minute and hours
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
minutes = 00;
seconds = 00;
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function() {
timeleft--;
$('.sec').text(timeleft);
if (timeleft == 0) {
clearInterval(downloadTimer);
$('#informationModal').fadeOut(400, startTimer);
minutes = 00;
seconds = 10;
}
}, 1000);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hour = (hour < 0) ? 59 : hour;
hour = (hour < 10) ? '0' + hour : hour;
timer2 = hour + ':' + minutes + ':' + seconds;
$('#countdown').html(timer2);
}, 1000);
}
startTimer();
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<!-- The Modal -->
<div id="informationModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p>Some text in the Modal..<span class="sec"></span></p>
</div>
</div>

This is to give you an idea how you could solve it with scoping your code in a function and then call that function over and over again.
var timer2 = "00 : 00 : 5";
var hour = 0;
var minutes = 0;
var seconds = 0;
var setupTime = function(time){
let timer = time.split(':');
hour = parseInt(timer[0], 10);
minutes = parseInt(timer[1], 10);
seconds = parseInt(timer[2], 10);
}
setupTime(timer2);
var myFunction = function(){
var interval = setInterval(function() {
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0 && seconds < 0) {
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function(){
timeleft--;
$('.sec').text(timeleft);
if(timeleft == 0){
clearInterval(downloadTimer);
$('#informationModal').fadeOut();
// resetTimer and call myFunction to start again
setupTime(timer2);
myFunction();
}
},1000);
} else {
$('#countdown').html(seconds);
}
}, 1000);
};
myFunction();
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<!-- The Modal -->
<div id="informationModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p>Some text in the Modal..<span class="sec"></span></p>
</div>
</div>
You need to be careful with variables if you change them from integers to strings. That's why the time is not visible as 00:00:00 but you will figure out how to solve that.
Side note: If you ask a question. Please always check your indents and fix them as long as you need to provide "clean" code. As it is no fun to fix indents to answer a question.

Related

How to make HH:MM:SS countdown timer, using javascript?

i've tried to make simple countdown timer, but i don't know how to make something when the timer ends and i don't know how to make timer with hours HH. I can make only minutes MM and second SS.
So, i have this HTML code:
<div class="tadc-time-display">
<span class="tadc-time-display-hours_minutes">00:00</span>
<span class="tadc-time-display-seconds">00</span>
</div>
The JS code i used to have is useless(
You can use Native JavaScript or jQuery, if you want)
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 0.1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
It should also start, stop and reset, but i dont know how to do it( Thanks a lot!
var hours = 0, // obtain these values somewhere else
minutes = 1,
seconds = 20,
target = new Date(),
timerDiv = document.getElementById("timer"),
handler;
function init() {
// set the target date time with the counter values
// counters more then 24h should have a date setup or it wont work
target.setHours(hours);
target.setMinutes(minutes);
target.setSeconds(seconds);
target.setMilliseconds(0); // make sure that miliseconds is 0
timerDiv.innerHTML = target.toTimeString().split(" ")[0]; // print the value
}
function updateTimer() {
var time = target.getTime();
target.setTime(time - 1000); // subtract 1 second with every thick
timerDiv.innerHTML = target.toTimeString().split(" ")[0];
if (
target.getHours() === 0 &&
target.getMinutes() === 0 &&
target.getSeconds() === 0
) { // counter should stop
clearInterval(handler);
}
}
handler = setInterval(updateTimer, 1000);
document.getElementById("stop-button").addEventListener("click", function() {
clearInterval(handler);
});
document.getElementById("start-button").addEventListener("click", function() {
clearInterval(handler);
handler = setInterval(updateTimer, 1000);
});
document.getElementById("reset-button").addEventListener("click", function() {
init();
clearInterval(handler);
});
init();
<div id="timer"></div>
<div>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<button id="reset-button">Reset</button>
</div>
Here is working sample with comments.
try this :
<html lang="en"><head>
<style>
#import "//fonts.googleapis.com/css?family=Bangers";
body {
margin: 0;
}
.wrap {
display: flex;
align-items: center;
justify-content: center;
background:#111;
}
.time-to {
text-align: center;
font-family: Bangers;
color: white;
font-size: 50px;
}
.underline {
text-decoration: underline;
}
.time-to span {
display: block;
font-size: 70px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<div class="wrap ng-scope" ng-app="app">
<div class="time-to">
prochain event dans :
<span countdown="" date="november 17, 2019 15:15:50" class="ng-isolate-scope underline"></span>
<br>
event : minecraft , ip: 144.76.116.78:40020
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script id="rendered-js">
(function () {
angular.module('app', []).directive('countdown', [
'Util',
'$interval',
function (Util,
$interval) {
return {
restrict: 'A',
scope: {
date: '#' },
link: function (scope,
element) {
var future;
future = new Date(scope.date);
$interval(function () {
var diff;
diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
return element.text(Util.dhms(diff));
},
1000);
} };
}]).
factory('Util', [
function () {
return {
dhms: function (t) {
var days,
hours,
minutes,
seconds;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
return [days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'].join(' ');
} };
}]);
}).call(this);
</script>
</body></html>

Instead of script src address attribute put source directly

I have a code that's working:
if (typeof Checkout === 'object') {
if (typeof Checkout.$ === 'function') {
(function(src) {
var tagName = 'script',
script = document.createElement(tagName);
script.src = src;
var head = document.getElementsByTagName('head')[0];
head.insertBefore(script, head.childNodes[0]);
})('https://www.conversionpirate.com/pirate-countdown.js');
}
}
But I don't want to have reference to conversionpirate site since it's plain js that I can directly paste there. The problem is I don't know how to do it - I tried to put pirate-countdown.js code inside that method but failed. I'm sure it's quite easy, but required knowledge about it. Could someone help me with this one?
Work normally just by adding html element with main__header class and time id as beleow :
<script src="https://www.conversionpirate.com/pirate-countdown.js"></script>
<div class="main__header">
</div>
<div id="time">
</div>
Also if your still facing probleme make directly their code into your js file or just create new js file and refernce it loccally :
see below snipet :
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fragment3 = create('<div style="background:#fff5d2;padding:10px 20px;border:1px solid #e3df74; font-size:14px; color:#2c2c2c; font-weight:bold;-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin:10px 0px 20px 0px">Your order is reserved for <span id="time"></span> minutes!</div>');
document.getElementsByClassName('main__header')[0].appendChild(fragment3);
var ten = 60 * 10,
display = document.querySelector('#time');
startTimer(ten, display);
};
<div class="main__header">
</div>
<div id="time">
</div>

Timer wont stop at 00:00

My countdown timer wont stop 00:00 it just keeps going until it reaches " -01:59 " then " -02:59 " and so on , I changed some of the code here and there but it still keeps going and going
<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;
function countdown() {
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--;
setTimeout('Decrement()', 1000);
}
}
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: should assign setTimeout to a variable, when secs is 0, clear the time out.
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 10;
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);
}
countdown();
<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>
Hope this helps.

Blinking image issues for javascript timer

I am having an issue with the timer I created. I just added in a code snippet that will cause a red rectangle to begin flashing(blinking) on the screen between 30 seconds and zero seconds. Once the timer hits zero the blinking needs to stop. The timer should only blink between 30 seconds and 0 seconds. For some reason my blinkRed() function is going haywire and I cannot figure out why. Sometimes it stops when it is supposed to other times it does whatever.
My code is below:
var seconds = 20; //Variables for the code below
var countdownTimer;
var imgBlink;
function showGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'visible';
};
function hideGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'hidden';
};
function showYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'visible';
};
function hideYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'hidden';
};
function blinkRed(){
var redBlink = document.getElementById('redStop');
if(redBlink.style.visibility == 'hidden'){
redBlink.style.visibility = 'visible';
} else {
redBlink.style.visibility = 'hidden';
}
imgBlink = setTimeout("blinkRed()", 1000);
};
function showRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'visible';
};
function hideRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'hidden';
};
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer);//keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 150) { //green between 5:00 - 1:30
//document.body.style.background = "url("+colorChange[0]+")";
showGreen();
}
else if (seconds <= 150 && seconds > 60) { //yellow between 1:30 - 30
//document.body.style.background = "url("+colorChange[1]+")";
hideGreen();
showYellow();
}
else if(seconds <= 60 && seconds > 30){ // red between 30 - 0
//document.body.style.background = "url("+colorChange[2]+")";
hideYellow();
showRed();
}
else if (seconds <= 30 && seconds > 0) {
hideRed();
blinkRed();
}
else if (seconds == 0){
clearTimeout(imgBlink);
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
//startDisabled2();
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
clearTimeout(imgBlink);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
hideGreen();
hideYellow();
hideRed();
};
#countdown{
font-size: 2em;
position: inherit;
left: 120px;
top: 5px;
}
#countdown2{
font-size: 2em;
position: inherit;
left: 120px;
top: 30px;
}
#greenGo{
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
#yellowAlmost{
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
#redStop {
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<script src = "Timer2.js">
</script>
</head>
<<div id = "timerBackground">
<span id="countdown" class="timer"></span>
<div id = "timerButtons">
<input type="button" value="Start" onclick="countdown(this)" id = "start">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<div id = "timerBackground2">
<span id="countdown2" class="timer"></span>
<div id = "timerButtons2">
<input type="button" value="Start" onclick="countdown(this)" id = "start2">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<img src = "greenGo.png" id = "greenGo" alt = "greenGo">
<img src = "redStop.png" id = "redStop" alt = "redStop">
<img src = "yellowAlmost.png" id = "yellowAlmost" alt = "yellowAlmost">
</body>
</html>
Ive attempted to add clearTimeout(imgBlink); to just about everything I can think of and nothing seems to work. It just keeps ticking away.
Just figured it out. I added:
imgBlink = setTimeout("blinkRed()", 1000);
if(seconds == 0){
clearTimeout(imgBlink);
}
Into the blinkRed() function and now it works like a charm. Although if you press the stop button twice it continues to tick. But that is a minor issue.
Here is the updated javascript.
var seconds = 20; //Variables for the code below
var countdownTimer;
var imgBlink;
/*function startDisabled2() {
start2.disabled == true;
if (start2.disabled == true) {
start.disabled = true;
}
};*/
function showGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'visible';
};
function hideGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'hidden';
};
function showYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'visible';
};
function hideYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'hidden';
};
function showRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'visible';
};
function hideRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'hidden';
};
function blinkRed(){
var redBlink = document.getElementById('redStop');
if(redBlink.style.visibility == 'hidden'){
redBlink.style.visibility = 'visible';
} else {
redBlink.style.visibility = 'hidden';
}
imgBlink = setTimeout("blinkRed()", 1000);
if(seconds == 0){
clearTimeout(imgBlink);
}
};
/*function stopBlinkRed() {
clearInterval(imgBlink);
};*/
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer);//keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 150) { //green between 5:00 - 1:30
//document.body.style.background = "url("+colorChange[0]+")";
showGreen();
}
else if (seconds <= 150 && seconds > 60) { //yellow between 1:30 - 30
//document.body.style.background = "url("+colorChange[1]+")";
hideGreen();
showYellow();
}
else if(seconds <= 60 && seconds > 30){ // red between 30 - 0
//document.body.style.background = "url("+colorChange[2]+")";
hideYellow();
showRed();
}
else if (seconds <= 30 && seconds > 0) {
hideRed();
blinkRed();
}
else if (seconds == 0){
showRed();
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
//startDisabled2();
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
clearTimeout(imgBlink);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
hideGreen();
hideYellow();
hideRed();
};

javascript countdown timer goes negative

I'm trying to implement a countdown timer on my mobile site using javascript. I've got this but the timer goes into negative, it doesn't stop. I want it to stop at 0:0.
JavaScript
// set minutes
var mins = 5;
// calculate seconds
var secs = mins * 60;
function countdown() {
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--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
HTML
<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; font-weight: bold;"> minutes and <input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;"> seconds.
</div>
And I'm also trying to change the font color countdown minute to red but it doesn't seem to change?
<input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; **font-color:red;** font-weight: bold;">
You are unconditionally setting setTimeout to repeat. Try if( secs > 0) setTimeout(Decrement,1000)
The CSS is color, not font-color
Your code is a mess too...
var time = 5 * 60,
start = Date.now(),
mins = document.getElementById('minutes'),
secs = document.getElementById('seconds'),
timer;
function countdown() {
var timeleft = Math.max(0, time - (Date.now() - start) / 1000),
m = Math.floor(timeleft / 60),
s = Math.floor(timeleft % 60);
mins.firstChild.nodeValue = m;
secs.firstChild.nodeValue = s;
if( timeleft == 0) clearInterval(timer);
}
timer = setInterval(countdown, 200);
<div id="timer">
This is only valid for the next <strong id="minutes">-</strong> minutes and <strong id="seconds">-</strong> seconds.
</div>
I did a quick simple counter you can use for your own sake
var mins=5;
var secs = mins*60;
var timerInterv = setInterval(doCountDown, 1000);
var outMins,outSecs
function doCountDown()
{
--secs;
if (secs<=0)
{ outMins=outSecs=0;
clearInterval(timerInterv);
return;
}
outMins = parseInt(secs/60);
outSecs = secs%60;
console.log("M:"+outMins+" S:"+outSecs);
}
You have to add check before decrementing secs
if (secs > 0) {
secs--;
setTimeout('Decrement()', 1000);
}
for font color add color:red in your style that refers on minutes

Categories