How can I prevent this daily countdown timer from resetting at midnight? - javascript

Key variables to keep in mind:
This is set to simulate 11:00 PM.
var bt = "23:00";
This is set to simulate 8:00 AM.
var wt = "08:00";
The desired functionality:
The countdown timer starts every morning at 8:00 AM.
It counts down until 11:00 PM, every night.
Then it stays at 00:00:00.
In the morning, at 8:00 AM, it repeats the count-down, again.
This should happen forever.
What is actually happening:
Everything is working fine, except it is starting a 24 hour countdown at midnight, until 8:00 AM.
I have tried debugging this, and I suspect the error lies in what is calculated as the distance variable, making the code think that it is comparing against the next day, but I am not sure how to remedy this.
Here is the Codepen.
and here is my JS code:
$(document).ready(function () {
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dateNow = moment().format('MMM D, YYYY');
placeHolderDate = dateNow + " " + bt;
var timeNow = moment().format('HH:mm');
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// Update the count down every 1 second
var x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
var timeNow = moment().format('HH:mm');
//console.log('Time Now:' + timeNow);
//console.log('Wake Time:' + wt);
if (timeNow === wt) {
clearInterval(x);
restartCountdown();
}
//console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
function restartCountdown() {
//log("restartCountdown Started!");
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dN = (moment().add(moment.duration({d: 1})).format('MMM D, YYYY'));
console.log('dn ' + dN);
var placeHolderDate = dN + " " + bt;
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// Update the count down every 1 second
var x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
// console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
}
});

I have edited your code and created this codepen https://codepen.io/anon/pen/aabjEb?editors=0010. Please feel free to optimize the code since I have not done it. The idea was is check if time is between 8 AM and 11 PM. If yes show value else show 00:00:00. Also once the date changes, update the dates and now compute accordingly
$(document).ready(function () {
function countdown() {
var bt = "23:00", // 11:00 PM
wt = "08:00"; // 08:00 AM
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth()+1,
yyyy = today.getFullYear();
var startTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + wt),
endTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + bt);
setInterval(function() {
var now = new Date();
var nowdd = today.getDate();
var nowTime = now.getTime();
if(dd !== nowdd) {
dd = nowdd;
var nowmm = now.getMonth() + 1,
nowyyyy = now.getFullYear();
startTime = new Date(dd + '/' + mm + '/' + yyyy + ' wt');
endTime = new Date(dd + '/' + mm + '/' + yyyy + ' bt');
}
if(nowTime > startTime && nowTime < endTime) {
// Find the distance between now and the count down date
var distance = endTime - nowTime;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
} else {
$("#countDown").val("00:00:00");
}
}, 1000);
}
countdown();
});

Related

How to make countdown time after 0 0 0 0 back to countdown again in javascript?

I just want to know how to make countdown after 0 0 0 0 its directly back to 23:59:59 so i have a problem when i try to create countdown function when its expired it will go to -0d -0h -0m -1s , -0d -0h -0m -2s but when i refresh it back to 23.59.58 , 23,59,57. i just want to know after clear interval it direcy go to 23.59.59 not -0d -0h -0m -0s . this is my script
countdown.js
function warTime2(countDownDate) {
var countDownDate = new Date();
countDownDate.setHours(14);
countDownDate.setMinutes(0);
countDownDate.setSeconds(0);
var now = new Date();
if (now.getHours() < countDownDate.getHours()) {
countDownDate = countDownDate;
} else if (countDownDate.getHours() <= now.getHours()) {
countDownDate.setDate(countDownDate.getDate() + 1);
}
var x = setInterval(function () {
var now = new Date();
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(
(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("second_chip_war").innerHTML =
"02:00 PM War Start in " + hours + ":" + minutes + ":" + seconds;
if (distance < 0) {
clearInterval(x);
let newDate = countDownDate + 8 * 3600 * 1000;
warTime2(newDate);
}
}, 1000);
}
Thank you, glad to hear if you want to help me
You need to check whether distance is less than 0 when you first assign it, and if so, increase countDownDate by a day before recomputing distance and continuing the function:
function warTime2(countDownDate) {
var countDownDate = new Date();
countDownDate.setHours(14);
countDownDate.setMinutes(0);
countDownDate.setSeconds(0);
var now = new Date();
if (now.getHours() < countDownDate.getHours()) {
countDownDate = countDownDate;
} else
if (countDownDate.getHours() <= now.getHours()) {
countDownDate.setDate(countDownDate.getDate() + 1);
}
var x = setInterval(function() {
var now = new Date();
var distance = countDownDate - now;
if (distance < 0) {
// countdown complete, add a day to countDownDate and restart
countDownDate.setDate(countDownDate.getDate() + 1);
distance = countDownDate - now;
}
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("second_chip_war").innerHTML = "02:00 PM War Start in " + hours + ":" +
minutes + ":" + seconds;
}, 1000);
}
warTime2('2020-06-21');
<div id="second_chip_war"></div>

Countdown doesn't reset for next year

We had this countdown for Christmas, but now it shows expired instead of resetting to next year
// Set the date we're counting down to
var year = new Date().getFullYear();
var countDownDate = new Date("Dec 24, " + year + " 23:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="clock"
document.getElementById("clock").innerHTML = days + " days " + hours + "hrs. " + minutes + "mins. " + seconds + "secs. ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
}, 1000);
The 'expired' message should maybe show during the 25-26th of December and then reset back to counting on 27th till next year?
I cant see where you check if your date is later than december, 26th, here should be code like this
if (days < -2) {
countDownDate = new Date("Dec 24, " + (year + 1) + " 23:00:00").getTime();
} else if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
or better just in the very beginning write
var now = new Date()
var year = now.getFullYear() + (now.getMonth() == 11 && now.getDate() > 26)
Below are suggested edits to your code. Near the top, we decide which year's Christmas to count down to.
If you look over the code and commments, you can see more about how date information can be used in JavaScript.
If you want to know more, there's great information at MDN's Date Object page.
// Get a Date object for the current time before starting the countdown
let startTime = new Date()
// Get the year, month and day from the date object
let year = startTime.getFullYear();
let monthIndex = startTime.getMonth();
let dayOfMonth = startTime.getDate();
//console.log (`${year} ${monthIndex} ${dayOfMonth}`);
if (monthIndex === 11 && dayOfMonth > 27){ // Jan has monthIndex == 0
year = year + 1; // Use next year
}
// Set the date we're counting down to
let countDownDate = new Date("Dec 24, " + year + " 23:00:00").getTime();
// Start the countdown, updating the display every 1 second
var x = setInterval(function() {
// Get a Date object for the current second of the countdown
var date = new Date()
// Get the timestamp from the Date object
var now = date.getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Function to show "day" if 1 day, "days" if 2 or more days, etc.
function pluralIfAppropriate(value, singularLabel, pluralLabel){
if(value == 1){
return singularLabel;
}
else{
if(pluralLabel == undefined){
pluralLabel = singularLabel + "s";
}
return pluralLabel;
}
}
// Builds the display text
let displayText = `${days} ${pluralIfAppropriate(days, "day")} ${hours}${pluralIfAppropriate(hours, "hr")} ${minutes}${pluralIfAppropriate(minutes, "min")} ${seconds}${pluralIfAppropriate(seconds, "sec")}`;
// Displays the displayText in the element with id="clock"
document.getElementById("clock").innerHTML = displayText;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
}, 1000);
<p id="clock"></p>

Show countdown timer in HH:MM:SS instead of H:M:S in Javascript

I managed to display a countdown timer in H:M:S format.
May I know how can I display it to HH:MM:SS format? Example, let's say for 300 hours, 1 minute and 1 second, it will display as 300:01:01 instead of 300:1:1 .
This is what I got so far.
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + " : "
+ minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
Test for values less than 10 and append a leading zero
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hours < 10) hours = '0'+ hours;
if (minutes < 10) minutes = '0'+ minutes;
if (seconds < 10) seconds = '0'+ seconds;
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + " : "
+ minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
As kamoroso94 mentioned in a comment, you could also use padstart()
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours.toString().padStart(2, '0') + " : "
+ minutes.toString().padStart(2, '0') + " : " + seconds.toString().padStart(2, '0') + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
You can prefix(aka padLeft) the hours, minutes and seconds with arbitrary length strings as below:
function padLeft(padding, data) {
return +(padding + data).slice(-padding.length);
}
padLeft('00', 3) // '03'
padLeft('00', 13) // '13'
padLeft('0000', 3) // '0003'
You can do this with a simple replace:
var timeString = (hours + ':' + minutes + ':' + seconds).replace(/\b(\d)\b/g, '0$1');
EDIT: in case you do not want to prepend a zero to the hours:
var timeString = (hours + ':' + minutes + ':' + seconds).replace(/:(\d)\b/g, ':0$1');
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = (`0${Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))}`).substr(-2); ;
var seconds = (`0${Math.floor((distance % (1000 * 60)) / 1000)}`).substr(-2);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = `${hours}:${minutes}:${seconds}`;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>

Set a GMT on a countdown script

How can I set a GMT to date.Now()?
var countDownDate = getNextDayOfWeek(new Date(),0,21);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString();
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString();
var seconds = Math.floor((distance % (1000 * 60)) / 1000).toString();
// Add 0 when value are < 10
hours = (hours < 10) ? "0"+hours : hours;
minutes = (minutes < 10) ? "0"+minutes : minutes;
seconds = (seconds < 10) ? "0"+seconds : seconds;
var grb = jq("#grb");
// Display the result in the element with id="grb"
grb.html(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
var one_hour = -60 * -60 * -1000;
if(distance < one_hour){
grb.html("GRB is finished!");
}else{
grb.html("GRB is open!");
}
}
}, 1000);
});
It keeps using the time of your computer, and I want to use a timezone to be stored everytime.
I have tried TimeZoneOffset, didn't worked, any help would be appreciated.
please see this
var now = new Date();
var nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var distance = end - nowUTC;

timer data start for next week

function countDown(){
// Set the date we're counting down to
var countDownDate = new Date("july 11, 2017 10:19:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
countDownDate = new Date("july 18, 2017 10:19:00").getTime();
}
}, 1000);
}
countDown();
what I want to reach is the every week the timer will start count to the next week.
I have something that start every week in the same day and in the same hour.
I don't want to rewrite the code every week :/
Thank you.
so why so much calculation is needed just to calculate how many seconds are remaining to start of next week? for example I am writing a sample code to calculate it.
function distranceToNextWeekStartInSeconds() {
var now = new Date()
var dayDiff = 7 - now.getDay();
var startOfNextWeek = new Date(now.valueOf());
startOfNextWeek.setDate(now.getDate() + dayDiff);
startOfNextWeek.setHours(0);
startOfNextWeek.setMinutes(0);
startOfNextWeek.setSeconds(0);
return Math.floor((startOfNextWeek - now) / 1000);
}
console.log('Seconds remaining to next week start: ' + distranceToNextWeekStartInSeconds())
and you can simply call this function inside your timer for a live calculation and display purpose, That's It.
I assumed you wanted to count down to every next tuesday at 10:19:00.
I'm too lazy right now to test every cases, ut I think it should work.
function getNextTuesday() {
// Get the date from now
var date = new Date();
// Set target hour/minute/seconds
date.setHours(10);
date.setMinutes(19);
date.setSeconds(0);
// Seek for the next tuesday
var actualDay = date.getDay();
var targetDay = 2; //Tuesday
// diff will give us the day span between today and the next tuesday
var diff = targetDay - actualDay;
// If the diff is less than 0 (we're sunday or monday, or we fall on the exact day, minutes after the target hour) then add a week
if (diff < 0 || (date.getTime() - new Date().getTime()) <= 0) {
diff += 7;
}
// Finally add the day span to the current date
date.setDate(date.getDate() + diff);
return date;
}
function countDown() {
// Set the date we're counting down to
var countDownDate = getNextTuesday();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (distance < 0) {
// If the count down is over, write some text
document.getElementById("demo").innerHTML = 'IT\'S HAPPENING !';
countDownDate = getNextTuesday();
} else {
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
}, 1000);
}
countDown();
<div id="demo"></div>

Categories

Resources