I have this countdown timer. For some reason it stops counting after one minute - it just stops.
If I count for 55 minutes it stops at 54:00
If I count for 2 minutes it stops at 1:00
Any ideas how do I fix that so it continues up to zero?
Here is the JSFiddle link: Countdown timer with cookies
And the JS code:
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if(getCookie("minutes")&&getCookie("seconds"))
{
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes",mins,10)
setCookie("seconds",seconds,10)
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
countdown(55);
I don't know why you are using the cookies here but, putting that aside, your problem seems to be the following lines:
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
In your code after you finished the first minute you call the countdown function again with a minute less. However, the lines above returns the minute variable back to its previous value. So you end up stuck in the same minute after one minute pass.
So, I assume, you need to get the time from the cookies only once (first time the countdown runs). You can use something like this:
var firstTime = true;
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if(firstTime && getCookie("minutes")&&getCookie("seconds"))
{
firstTime = false;
seconds = getCookie("seconds");
mins = getCookie("minutes");
}
...
Note that var is unnecessary in the if clause since you already
defined seconds and mins variables.
Code with day:hours:minute:second support.
Just add number of minutes into timer span.
For one day test, I entered 1440 minutes.
<html>
<body>
<span id="countdown" class="timer">1440</span>
<script type="text/javascript">
var first_time = true;
var countdownTimer;
var seconds = document.getElementById('countdown').innerHTML * 60;
//alert(seconds);
if(!isNaN(seconds) && seconds > 0 ) {
function timer() {
if(first_time) {
countdownTimer = setInterval('timer()', 1000);
first_time = false;
}
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = (days < 10 ? "0" : "") + days + ":" + (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
timer()
//var countdownTimer = setInterval('timer()', 1000);
}
</script>
</body>
</html>
Related
Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});
Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
I want to create a simple countdown timer, I found something its working only for seconds, I want to add hours:minutes:seconds...
how can I make the same timer for hh:mm:ss
<script type="text/javascript">
var seconds;
var temp;
function countdown() {
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, 10);
if (seconds == 1) {
temp = document.getElementById('countdown');
temp.innerHTML = "00";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown();
</script>
var seconds;
var temp;
function countdown() {
time = document.getElementById('countdown').innerHTML;
timeArray = time.split(':')
seconds = timeToSeconds(timeArray);
if (seconds == '') {
temp = document.getElementById('countdown');
temp.innerHTML = "00:00:00";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = secondsToTime(seconds);
timeoutMyOswego = setTimeout(countdown, 1000);
}
function timeToSeconds(timeArray) {
var minutes = (timeArray[0] * 60) + (timeArray[1] * 1);
var seconds = (minutes * 60) + (timeArray[2] * 1);
return seconds;
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
hours = hours < 10 ? '0' + hours : hours;
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
minutes = minutes < 10 ? '0' + minutes : minutes;
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
seconds = seconds < 10 ? '0' + seconds : seconds;
return hours + ':' + minutes + ':' + seconds;
}
countdown();
<div id="countdown">01:02:15</div>
You may have different variables and different inner html's for the each part of your timer as hours for "hh", minutes for "mm" and seconds for "ss".. and for every step set the inner htmls equal to variables.
Initialize hours with some number and make it countdown by 1 when the others are zero and at the same time make the minutes and seconds equal to 59 and start counting down the seconds as the code you added above, then same thing goes for the minutes-seconds relation (when seconds are zero and minutes are not zero countdown minutes by one). At the end return if all the variables are zero..
Hope this helps..
You didn't say if you want to count up or down so here is a solution for both, just take the parts of the code you need:
(Fiddle: http://jsfiddle.net/Luc4oqo8/2/)
(I used jQuery here, you should use it too because its awesome)
HTML:
<div id="counter_up">
<p id="h">00</p>:<p id="m">00</p>:<p id="s">00</p>
</div>
<div id="counter_dn">
<p id="h">00</p>:<p id="m">00</p>:<p id="s">00</p>
</div>
JS:
var h_up = GetElementInsideContainer ("counter_up", "h");
var m_up = GetElementInsideContainer ("counter_up", "m");
var s_up = GetElementInsideContainer ("counter_up", "s");
var h_dn = GetElementInsideContainer ("counter_dn", "h");
var m_dn = GetElementInsideContainer ("counter_dn", "m");
var s_dn = GetElementInsideContainer ("counter_dn", "s");
// THIS COUNTS UP
setInterval ( function()
{
if (parseInt(s_up.innerHTML) < 59)
{
s_up.innerHTML = parseInt(s_up.innerHTML) + 1;
if (parseInt(s_up.innerHTML) < 10)
s_up.innerHTML = "0" + s_up.innerHTML;
}
else
{
s_up.innerHTML = 0;
if (parseInt(m_up.innerHTML) < 59)
{
m_up.innerHTML = parseInt(m_up.innerHTML) + 1;
if (parseInt(m_up.innerHTML) < 10)
m_up.innerHTML = "0" + m_up.innerHTML;
}
else
{
m_up.innerHTML = 0;
if (parseInt (h_up.innerHTML) < 23)
{
h_up.innerHTML = parseInt(h_up.innerHTML) + 1;
if (parseInt(h_up.innerHTML) < 10)
h_up.innerHTML = "0" + h_up.innerHTML;
}
else
{
h_up.innerHTML = m_up.innherHTML = s_up.innerHTML = 0;
}
};
}
}, 1000);
// THIS COUNTS DOWN
setInterval ( function()
{
if (parseInt(s_dn.innerHTML) > 0)
{
s_dn.innerHTML = parseInt(s_dn.innerHTML) - 1;
if (parseInt(s_dn.innerHTML) < 10)
s_dn.innerHTML = "0" + s_dn.innerHTML;
}
else
{
s_dn.innerHTML = 59;
if (parseInt(m_dn.innerHTML) > 0)
{
m_dn.innerHTML = parseInt(m_dn.innerHTML) - 1;
if (parseInt(m_dn.innerHTML) < 10)
m_dn.innerHTML = "0" + m_dn.innerHTML;
}
else
{
m_dn.innerHTML = 59;
if (parseInt (h_dn.innerHTML) > 0)
{
h_dn.innerHTML = parseInt(h_dn.innerHTML) - 1;
if (parseInt(h_dn.innerHTML) < 10)
h_dn.innerHTML = "0" + h_dn.innerHTML;
}
else
{
h_dn.innerHTML = 23;
m_dn.innherHTML = s_dn.innerHTML = 59;
}
};
}
}, 1000);
// Very useful, got it from here: http://stackoverflow.com/questions/7171483/simple-way-to-get-element-by-id-within-a-div-tag
function GetElementInsideContainer(containerID, childID)
{
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName("*");
for (var i = 0; i < elms.length; i++)
{
if (elms[i].id === childID)
{
elm = elms[i];
break;
}
}
return elm;
}
CSS:
p
{
display: inline-block;
}
if you have Seconds get hours and minutes as follow
var hours = parseInt( Your seconds here / 3600 ) % 24;
var minutes = parseInt( Your seconds here / 60 ) % 60;
var seconds = Your seconds here % 60;
here your complete time in HH:MM:SS
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
Sort and sweet approach
This is the code I have. Very messy, but due to my inexperience I can't detect why it does not work. By my counts the Decrements are js standard, at least for the milliseconds, seconds and minutes, not sure about the hours.
Here's the code. Thanks in advance.
<!DOCTYPE html>
<html>
<body>
<span id="tHours"></span>:<span id="tMins"></span>:<span id="tSeconds"></span>:<span id="tMilli"></span>
<script>
var hours = 1;
var mins = hours * 60;
var secs = mins * 60;
var mill = secs * 100;
var currentHours = 0;
var currentSeconds = 0;
var currentMinutes = 0;
vas currentMilli = 0;
setTimeout('DecrementMilli()',100);
setTimeout('DecrementSeconds()',1000);
setTimeout('DecrementMinutes()',10000);
setTimeout('DecrementHours()',100000);
function DecrementMilli() {
currentMilli = secs % 100;
if(currentMilli <= 99) currentMilli = "000" + currentMilli;
secs--;
document.getElementById("tMilli").innerHTML = currentMilli;
if(mill !== -1) setTimeout('Decrement()',100);
}
function DecrementSeconds() {
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("tSeconds").innerHTML = currentSeconds;
if(secs !== -1) setTimeout('Decrement()',1000);
}
function DecrementMinutes() {
currentMinutes = Math.round(secs / 60);
if(currentMinutes <= 60) currentMinutes = "00";
mins--;
document.getElementById("tMins").innerHTML = currentMinutes;
if(mins !== -1) setTimeout('Decrement()',10000);
}
function DecrementHours() {
currentHours = Math.round(1440 / 60);
if(currentHours <= 24) currentHours - 1;
hours--;
document.getElementById("tHours").innerHTML = currentHours;
if(hours !== -1) setTimeout('Decrement()',100000);
}
</script>
</body>
</html>
The time in your intervals is wrong. You can try the code below. Just put thee vars in your html, like:
<span id='tHours'>23</span>:<span id='tMins'>59</span>:<span id='tSeconds'>59</span>:<span id='tMilli'>99</span>
And the js like:
var milli = 99;
var sec = 59;
var min = 59;
var hour = 23;
setInterval(function () {
milli = milli == 0 ? 99 : milli - 1;
$('#tMilli').text(double0(milli));
},10);
setInterval(function () {
sec = sec == 0 ? 59 : sec - 1;
$('#tSec').text(double0(sec));
},1000);
setInterval(function () {
min = min == 0 ? 59 : min - 1;
$('#tMin').text(double0(min));
},60000);
setInterval(function () {
hour = hour == 0 ? 23 : hour - 1;
$('#tHour').text(double0(hour));
},1440000);
function double0 (num) {
num = num.toString().length == 1 ? '0' + num : num;
return num;
}
Well, I solved my own problem, but it's inelegant since it does not start at 24:00:00 but at 23:59:59. But it's a start.
I'll post it here in case it helps anyone
<script type="text/javascript">
var count = 86400;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
</script>
<span id='timer'></span>
I want to show clock with some difference . below given code is working fine for me. but i want to push and play this time whenever user want. i want to push and resume SetTimeout function .any one have any idea how to do that ?
$("#push").click(function () {
});
$("#play").click(function () {
show();
});
function show() {
var Digital = new Date();
var time2 = Digital.getTime();
var time1 = 1403517957984;
var diff = Math.abs(new Date(time2) - new Date(time1));
var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('#worked_time').html(hours + ":" + minutes + ":" + seconds);
setTimeout("show()", 1000);
}
show();
This is a mix of the respond of #colburton and #TwiStar
Respond correctly to the answer
var isPlaying = true;
var toHandle = null;
$("#push").click(function () {
isPlaying = false;
if (toHandle !== null)
{
clearTimeout(toHandle);
toHandle = null;
}
});
$("#play").click(function () {
isPlaying = true;
show();
});
function show() {
if (isPlaying) {
toHandle = null;
var Digital = new Date();
var time2 = Digital.getTime();
var time1 = 1403517957984;
var diff = Math.abs(new Date(time2) - new Date(time1));
var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('#worked_time').html(hours + ":" + minutes + ":" + seconds);
toHandle = setTimeout("show()", 1000);
}
}
show();
Save the handle to a variable:
var toHandle = null;
// start timeout
toHandle = setTimeout("show()", 1000);
Then you can cancel the timeout any time you want with:
// cancel timeout
if (toHandle) {
clearTimeout(toHandle);
toHandle = null;
}
Quick and dirty. Surround you show-function with an if which checks a "should i show the time"-flag:
var doShow = true;
$("#push").click(function () {
doShow = false;
});
$("#play").click(function () {
doShow = true;
show();
});
function show() {
if(doShow == true) {
var Digital = new Date();
var time2 = Digital.getTime();
var time1 = 1403517957984;
var diff = Math.abs(new Date(time2) - new Date(time1));
var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('#worked_time').html(hours + ":" + minutes + ":" + seconds);
setTimeout("show()", 1000);
}
}
show();
I need help with countdown timer in javascript.I found the code below in PHPJabbers. This code works fine, but when I reload the page the time goes back to its initial time. I want to retain the time even if I load the page. I want also to add PHP function inside if seconds == 0. I'm not sure if it's possible. Thanks in advance
<span id="countdown" class="timer"></span>
<script>
var seconds = 60;
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) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
Check this, (implemented using cookies)
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
//check existing cookie
cook=getCookie("my_cookie");
if(cook==""){
//cookie not found, so set seconds=60
var seconds = 60;
}else{
seconds = cook;
console.log(cook);
}
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
//store seconds to cookie
setCookie("my_cookie",seconds,5); //here 5 is expiry days
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
working jsFiddle
Nice solution by bhavesh.. If someone wants to show the days,hour,mins, seconds together then they can refer this code.
Reverse timer from javascript:
var target_date = new Date('Aug 01 2014 20:47:00').getTime();
var days, hours, minutes, seconds;
var countdown = document.getElementById('timeremaining');
var countdownTimer = setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0 )
{
document.getElementById('timeremaining').innerHTML = '';
clearInterval(countdownTimer);
}
else
{
if(days>0)
{
days= days+'d,';
}
else
{
days='';
}
countdown.innerHTML ='( ' + days + checkTime(hours) + ':'+ checkTime(minutes) + ':' + checkTime(seconds) +' remaining)';
}
}, 1000);
function checkTime(i) {
if (i < 10) {i = '0' + i};
return i;
}