简体   繁体   中英

Everyday countdown using Javascript

I would like to create a simple Daily CountDown using JavaScript. The countdown should work similarly to this: https://www.w3schools.com/howto/howto_js_countdown.asp

 // Set the date we're counting down to var countDownDate = new Date("Jan 5, 2022 15:37:25").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); // 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) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 1000);

But instead of counting down to the fixed value of var CountDownDate, I would like the countdown to re-start every day at 3 PM.

Could anyone suggest appropriate amendments to the code above to achieve desired functionality or feel free to write a new code.

Many thanks for any input!

EDIT: Just to address your questions and elaborate further - I simply need a countdown that notifies my customers that they have only so much time left to order today IF they want the same-day-shipping. In other words, if you want your products to be dispatched TODAY you have 1hr:2min:3sec left. When the timer reaches 0 (at 3 PM) I want it to re-start to the 24hour mark and obviously expire again at 3 pm the following day. I would love it to take into consideration user's unique timezone. Hope that makes sense.

Create a Date equaling 3 PM today. If it's already past 3 PM today, add 24 hours, making it 3 PM tomorrow.

const now = new Date();
const countDownHour = 15;
let countDownDate = new Date(
   now.getFullYear(),
   now.getMonth(),
   now.getDate(),
   countDownHour
);
if (now.getHours() >= countDownHour) {
    countDownDate = new Date(countDownDate.getTime() + 24 * 60 * 60 * 1000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM