I'm having a problem with a count down timer made in JavaScript. It was working for the last 2 weeks, but today it started to show NaN:NaN... , and I can't understand why. Here is the code, does anyone have any idea which one could be the problem?
<div id="countdownmain">
<span id="countdownmain" class="timer"></span>
</div>
<script>
var date = new Date;
var secondsnow = date.getSeconds();
var minutesnow = date.getMinutes();
var hournow = date.getHours();
var day = date.getDay();
var passatti = (secondsnow + (minutesnow*60) + (hournow*3600));
if((day==1)||(day==2)||(day==3)||(day==4)){
if(passatti < 46800){
var upgradeTime = 46800 - passatti;
}else if(passatti > 46800){
var upgradeTime = 86400 - passatti + 46800;
}
}else if((day==5)&&(passatti < 46800)){
var upgradeTime = 46800 - passatti;
}else if((day==5)&&(passatti > 46800)){
var upgradeTime = 86400 - passatti + 46800 + 86400 + 86400;
}else if((day==6)){
var upgradeTime = 86400 - passatti + 46800 + 86400;
}else if((day==7)){
var upgradeTime = 86400 - passatti + 46800;
}
var seconds = upgradeTime;
function timer() {
var now = Math.floor(Date.now() / 1000);
('0' + 11).slice(-2)
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('countdownmain').innerHTML = "<span class='timesm'> For same working day dispatch, order in </span><br class='appear'><span style='display:inline-block; width:45px;'><span class='hideDays glowW'>" + ('0' + days).slice(-2) + "</span></span><span class='times'> days </span><span style='display:inline-block; width:45px;'><span class='hideHours glowW'>" + ('0' + hours).slice(-2) + "</span></span><span class='times'> hours </span><span style='display:inline-block; width:45px;'><span class='hideMinutes glowW'>" + ('0' + minutes).slice(-2) + "</span></span><span class='times'> minutes </span><span style='display:inline-block; width:45px;'><span class='hideSec glowW'>" + ('0' + remainingSeconds).slice(-2) + "</span></span><span class='times'> seconds </span>";
if (seconds == 0) {
clearInterval(countdownTimer);
//document.getElementById('countdownmain').innerHTML = "Completed";
seconds = upgradeTime;
} else {
seconds--;
$('.hideSec').fadeOut('slow');
}
if(('0' + remainingSeconds).slice(-2)==00){
$('.hideMinutes').fadeOut('slow');
}
if((('0' + minutes).slice(-2)==00)&&(('0' + remainingSeconds).slice(-2)==00)){
$('.hideHours').fadeOut('slow');
}
if((('0' + hours).slice(-2)==00)&&(('0' + minutes).slice(-2)==00)&&(('0' + remainingSeconds).slice(-2)==00)){
$('.hideDays').fadeOut('slow');
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
Unfortunately, today is Sunday! Javascript return 0 value as first of a week in getDay().
Take a look my fiddle. I just decreased day comparator value in if statement. (e.g. 1 -> 0, 2 -> 1, 3 -> 2 and so on..)
Related
I made this countdown timer to show a video after it reaches the end. However it just goes into negative numbers. Seems to be related to the part of the code to hide the content after expiry date. Here is a JS fiddle
<div id="countdown"></div>
<div id="playsession"></div>
<script>
var releaseDate = new Date('05/29/2021 9:00 UTC+1');
var expiryDate = new Date('10/11/2021 01:00AM UTC+1');
var cdNotice = 'This session will appear automatically when the countdown finishes';
var trDay = ' Days';
var trHours = ' Hours';
var trMin = ' Minutes';
var trSec = ' Seconds';
var media = "<div class=\"wistia_responsive_padding\" style=\"padding:56.25% 0 0 0;position:relative;\"><div class=\"wistia_responsive_wrapper\" style=\"height:100%;left:0;position:absolute;top:0;width:100%;\"><iframe src=\"https:\/\/fast.wistia.net\/embed\/iframe\/eiwj630vxa?videoFoam=true\" title=\"June 19 & 20 ~ Refresh & Revive ~ Gen Rabten ~ 1 Video\" allow=\"autoplay; fullscreen\" allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\" class=\"wistia_embed\" name=\"wistia_embed\" allowfullscreen msallowfullscreen width=\"100%\" height=\"100%\"><\/iframe><\/div><\/div>\r\n<script src=\"https:\/\/fast.wistia.net\/assets\/external\/E-v1.js\" async><\/script>";
</script>
Above I set the start time and expiry time.
If the person loads the page before the countdown ends it should show the countdown. If the person loads after the countdown it will show the video.
If the person loads the page after the expiry time it should show the expired message.
Timer
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = releaseDate - now;
var gone = expiryDate - now;
if (distance < 0 && gone > 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = "";
document.getElementById('playsession').innerHTML = media;
return;
}
if (gone < 0) {
clearInterval(timer);
document.getElementById('playsession').innerHTML = '<p>This video has now expired</p>';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = '<p>' + cdNotice + '</p>';
document.getElementById('countdown').innerHTML += '<p>';
if (days > 0) {
document.getElementById('countdown').innerHTML += '<b>' + days + trDay + '</b> ';
}
if (hours > 0) {
document.getElementById('countdown').innerHTML += '<b>' + hours + trHours + '</b> ';
}
if (minutes > 0) {
document.getElementById('countdown').innerHTML += '<b>' + minutes + trMin + '</b> ';
}
document.getElementById('countdown').innerHTML += '<b>' + seconds + trSec +'</b>';
document.getElementById('countdown').innerHTML += '</p>';
}
timer = setInterval(showRemaining, 1000);
Your expire date is incorrect, add space before AM, then it will work, otherwise your condition is not met, because gone = NaN.
With this it works correctly:
var expiryDate = new Date('10/11/2021 01:00 AM UTC+1')
I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?
Here is my code:
function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
and here is the code behind utcHours
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
Example here: http://codepen.io/markgamb/pen/gwGkbo
The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.
function solveTime(x) {
if (x < 0) {
var shift = 24 + x;
} else {
var shift = x;
}
var suffixSolve = (utcHours + shift) % 24;
var suffix = "am";
if (suffixSolve > 12) {
suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>
I have countdown time for 15 seconds. It refreshes when 1 second on it. I also need refresh timer when user clicks at link on my website. I use cookie to provide no refreshing of timer when user refreshes page. Now when I click at link my timer refreshes but my old timer continues to countdown. As a result I have two timers and every second I see values from different timers. For example: I have countdown timer for 15 second. I click at link when value on timer was 7 seconds, and I see something like this: 15, 6, 14, 5, 13, 4, 12, 3 etc. But I need normal sequnce such 15, 14, 13 etc. What should I do for it? Below is my code:
// calls when I click at link
function rate(auct_id){
$.ajax({
type: 'POST',
url: '/auth/rate',
data: {'id': auct_id },
success: function(data) {
data = jQuery.parseJSON(data);
if (data.message) {
alert(data.message);
if (data.message != 'rates_count') {
windows.location = '/#openModal';
}
} else {
var new_price = data.price;
var new_login = data.login;
new_price += '<span> руб.</span>';
$('#price_' + auct_id).html(new_price);
$('#login_' + auct_id).html(new_login);
setTimer(auct_id, true);
}
}
});
}
function setTimer(id, update) {
var countdown4;
if(getCookie('countdown_' + id) && !update) countdown4 = getCookie('countdown_' + id);
else countdown4 = 15;
if (update) delete_cookie('countdown_' + id);
do_cd4(id, countdown4, update);
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
function convert_to_time(secs) {
secs = parseInt(secs);
hh = secs / 3600;
hh = parseInt(hh);
mmt = secs - (hh * 3600);
mm = mmt / 60;
mm = parseInt(mm);
ss = mmt - (mm * 60);
if (hh > 23) {
dd = hh / 24;
dd = parseInt(dd);
hh = hh - (dd * 24);
} else {
dd = 0;
}
if (ss < 10) {
ss = "0" + ss;
}
if (mm < 10) {
mm = "0" + mm;
}
if (hh < 10) {
hh = "0" + hh;
}
if (dd == 0) {
return (hh + ":" + mm + ":" + ss);
}
else {
if (dd > 1) {
return (dd + " day " + hh + ":" + mm + ":" + ss);
} else {
return (dd + " day " + hh + ":" + mm + ":" + ss);
}
}
}
// Our function that will do the actual countdown
do_cd4 = function(id, countdown4, update) {
//console.log(countdown4);
if (countdown4 < 1) {
countdown4 = 15;
do_cd4(id, countdown4);
} else {
$('#timer_' + id).html(convert_to_time(countdown4));
setTimeout(function() {
do_cd4(id, countdown4, update);
}, 1000);
}
setCookie('countdown_' + id, countdown4, 3);
countdown4 = countdown4 - 1;
}
The question has already been asked : Resetting a setTimeout
You need to keep a reference on your setTimeout, so you can clear it or restart it.
I've gone over this for hours trying different things and can't get it to work, I've made a dice that rolls every 10 seconds, the timer and the dice roll shows on screen and constantly updates the roll. I want to make a box that shows the previous 5 rolls of the dice and constantly updates. Not sure if I have to make separate function or add it to my existing function. Here is what I have so far.
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".";
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
</script>
One option would be to have 5 predefined divs and have them cleared/filled dynamically.
Another option is to keep the roll history in an array and fill the 'history element' from that array.
For example:
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
where rolls is the array containing the history. (rollhistory is a class I made up to format the results).
In the underlying example I took the liberty of restructuring the program to display the above (click here for fiddle ) :
var die1 = document.getElementById("die1"),
status = document.getElementById("status");
function startTimer(secs) {
var timeInSecs = parseInt(secs),
rolls = [],
rem = 0,
maxrollhistory = 5,
roll = function(){
var d1 = Math.floor(Math.random() * 6) + 1;
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
status.innerHTML = "Dice Roll "+ d1 +".";
},
tick = function(){
if (--rem <= 0) {
rem = timeInSecs;
roll();
}
var secs = rem;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
setTimeout(tick,1000);
}
tick();
}
startTimer(10);
All you need is to append. Check the snippet added status.innerHTML += "Dice Roll "+diceTotal+".<br>";
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".<br>" +status.innerHTML;
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
<div id="countdown"></div> <div id="die1" class="dice">0</div> <h2 id="status" style="clear:centre;"></h2>
I have developed a JSP page. On this page, I have a count-down timer that displays time in hh:mm:ss. A link is provided to the previous page (page 2) from this page. After some work on page 2, control will be transferred to page 1 again.
I have a timer that starts when page 1 loads. When I go to page 2 and return to page 1, the timer gets refreshed. How can I make it start from where it was when I left the page?
Here's my timer code:
<script language="JavaScript">
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n ) {
return (n <= 9 ? "0" + n : n);
}
function getCurrentTime() {
time = new Date();
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
alert(hours + " " + mins + " " + secs);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if ( msLeft < 999 ) {
alert("please save your work and send your file!");
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits(secs);
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
if( hours == 0 && mins == 0 && secs == 59 ) alert("dsdsdsdsdsd");
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie ( name ) {
var cname = name + "=";
var dc = document.cookie;
if ( dc.length > 0 ) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
</script>
I think you can use cookies to store the current time and one flag=true before you switch to page 2; when you come back to page 1 you de-active flag=false to continue to calculate the time.
you can do follow steps below:
1) create a js file with content:
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
2) At form 1 before click to go to form 2, you can set the current time to cookie.
setCookie("tracking_time", time_string, 5);
Please refer Javascript Date Time functions to know how to get/set a time string
3) when come back to form 1 from form 2, you can get time value from cookie , then you set to timer to continue count time.
var time_string = getCookie("tracking_time");
Then you parse time_string to object
This is a sample complete code
<html>
<head>
</head>
<body>
<span id="countdown">Start</span>
<script>
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
var countdown = document.getElementById("countdown");
var days, hours, minutes, seconds;
var target_date = getCookie("tracking_time");
if (target_date == null) {
target_date = new Date().getTime() + (2*60*60*1000); // set countdown 2 hours
}
function updateTimer() {
setInterval(function () {
// this line below will set to function that user click on link to go to form 2
setCookie("tracking_time", target_date, 1);
// End line
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
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);
// format countdown string + set tag value
countdown.innerHTML = hours + "h: " + minutes + "m: " + seconds + "s";
}, 1000);
}
updateTimer();
</script>
</body>
</html>