JSFiddle - React, Tailwind, and code Playground
by Sascha
HTML
Today is <span id="day_name_today"></span>. Target day would be <span id="day_name_target"></span>.<br /> Remaining: <span id="days">
</span> days,
<span id="hours">
</span>:<span id="minutes">
</span>:<span id="seconds">
</span>
JavaScript
var curday;
var secTime;
var ticker;
var arrDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
function getSeconds() {
var nowDate = new Date();
var destinationDay;
var weekDay = nowDate.getDay() + 1; // to emulate another day, change the offset;
// as the author wants the countdown to elapse at 8 PM, add one day in case 8 PM has passed.
if (nowDate.getHours() >= 20) {
weekDay++;
}
// in case it is saturday passed 8 PM we would have a 7 as week day which should be changed to 0 (sunday).
weekDay = weekDay % 7;
document.getElementById('day_name_today').innerHTML = arrDayNames[weekDay];
if (weekDay > 1 && weekDay <= 3) {
destinationDay = 3;
} else if (weekDay > 3 && weekDay <= 5) {
destinationDay = 5;
} else {
destinationDay = 1;
}
document.getElementById('day_name_target').innerHTML = arrDayNames[destinationDay];
var counterTime = new Date();
counterTime.setDate(counterTime.getDate() + (destinationDay + 7 - weekDay) % 7);
counterTime.setHours(20);
counterTime.setMinutes(0);
counterTime.setSeconds(0);
var currentTime = nowDate.getTime(); //current time
var destinationTime = counterTime.getTime(); //countdown time
var diff = parseInt((destinationTime - currentTime) / 1000);
startTimer(diff);
}
function startTimer(secs) {
secTime = parseInt(secs);
ticker = window.setInterval(function() {
tick()
}, 1000);
tick(); //initial count display
}
function tick() {
var secs = secTime;
if (secs > 0) {
secTime--;
} else {
clearInterval(ticker);
getSeconds(); //start over
}
var days = Math.floor(secs / 86400);
secs %= 86400;
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
//update the time display
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = ((hours < 10) ? "0" : "") + hours;
document.getElementById("minutes").innerHTML =...