Here is the code I use to create a weekly repeating countdown timer. It works well, but I would like to expand on the following:
How can use this code twice on a single page without conflicts?
Currently, copying all elements and adjusting the "expiry" doesn't
work. I would like this to display two separate outputs with different expiry
dates.
Output is in the following format: hours, mins, and seconds. How can it
display only the most relevant information? For example, if there
are 10 hours 12 minutes, and 10 seconds left, it would display: 10
hours only(excluding mins and seconds). Similarly, if there were 00
hours 00 minutes and 10 seconds left it would instead display: 10
seconds (excluding mins and hours). The same would go for minutes (excluding hours and seconds).
Any insight would be most appreciated.
Repeating Countdown Timer Javascript
<script>
var curday;
var secTime;
var ticker;
function getSeconds() {
var nowDate = new Date();
var dy = 1 ; //Sunday through Saturday, 0 to 6
var countertime = new Date(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate(),21,0,0); //20 out of 24 hours = 8pm
var curtime = nowDate.getTime(); //current time
var atime = countertime.getTime(); //countdown time
var diff = parseInt((atime - curtime)/1000);
if (diff > 0) { curday = dy - nowDate.getDay() }
else { curday = dy - nowDate.getDay() -1 } //after countdown time
if (curday < 0) { curday += 7; } //already after countdown time, switch to next week
if (diff <= 0) { diff += (86400 * 7) }
startTimer (diff);
}
function startTimer(secs) {
secTime = parseInt(secs);
ticker = setInterval("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 = curday;
document.getElementById("hours").innerHTML = ((hours < 10 ) ? "0" : "" ) + hours;
document.getElementById("minutes").innerHTML = ( (mins < 10) ? "0" : "" ) + mins;
document.getElementById("seconds").innerHTML = ( (secs < 10) ? "0" : "" ) + secs;
}
</script>
Call getSeconds() function to start timer with body onload
<body onload="getSeconds();">
</body>
Timer Display HTML
<h6>Live in <span class="days" id="days"></span><span class="smalltext"> days,</span>
<span class="hours" id="hours"></span><span class="smalltext"> hours,</span>
<span class="minutes" id="minutes"></span><span class="smalltext"> minutes</span>
</h6>
You can simply do it like this
//create a javascript timer function
function timerCountDOwn(date, id) {
const el = document.getElementById(id)
if (!el) return
let countDownDate = new Date(date).getTime()
const timer = setInterval(function () {
const now = new Date().getTime(),
distance = countDownDate - now,
days = Math.floor(distance / (1000 * 60 * 60 * 24)),
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),
//Format your output here
output = `<span class="days">${days}D</span> <span class="hours">${hours}H</span> <span class="minutes">${minutes}M</span> <span class="seconds">${seconds}S</span>`
el.innerHTML = output
if (distance < 0) {
clearInterval(timer)
el.innerHTML = 'EXPIRED'
}
}, 1000)
}
// then you can use it on multiple element in a single page
timerCountDOwn('Jan 5, 2023 00:00:00', 'timer1')
timerCountDOwn('Aug 25, 2022 00:00:00', 'timer2')
timerCountDOwn('Oct 30, 2022 15:22:54', 'timer3')
.timer > span {
display: inline-block;
background: #db0808;
color: #fff;
padding: 5px 10px;
border-radius: 5px;
}
<div id="timer1" class="timer">...</div>
<div id="timer2" class="timer">...</div>
<div id="timer3" class="timer">...</div>
Related
I have ecommerce website. In that for same day delivery need to order before 11. So before 30 minutes of the end time(i.e. 11) i want to show that timer section.
Below code I am trying But getting issue how to set timer functionality.
setInterval(function(){
var secs = 1800;
var date = new Date;
// date.setTime(result_from_Date_getTime);
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();
console.log("Hour"+hour+"Minutes"+minutes+"seconds"+seconds);
// console.log(minutes);
// console.log(seconds);
if(hour == 10 && minutes>=30)
{
var mins = secs / 60;
console.log("Timer"+mins);
$('.top-header-content1').removeClass('hide-ticker1');
}
else if (hour >= 11){
console.log("hii11");
$('.top-header-content1').addClass('hide-ticker1');
}
secs--;
},1000);
If anyone have a idea , how to add time please let me know
Hi you use this code below:
/// the counting date
var countDownDate = new Date("Jan 5, 2024 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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
The following code will start a setInterval() in which during a time window between 10:30h and 11:00h a countdown will be shown. Before 10:30h and after 11:00h different messages are shown. And after 11:00h the setInterval is cleared.
// div for output on page:
const demo=document.getElementById("demo"),
// today's date
today = new Date();
today.setHours(11);today.setMinutes(0);today.setSeconds(0);
today.intv=setInterval(checkTime,1000);
function checkTime(){
const now=new Date();
if (now>today) {
demo.textContent="Order today for tomorrow's delivery.";
clearInterval(today.intv);
}
else if (now>(today-1800000)){
let tsec=Math.floor((today-now)/1000),
sec=tsec%60,
min=(tsec-sec)/60;
demo.textContent=`${min} minutes and ${sec} seconds left if you want to order for today's delivery.`;
} else
demo.textContent="Order now for today's delivery!"
}
<p id="demo"></p>
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>
I'm creating a system where I have to check the deadline based on the client's initialization. For example, if the client's initialization was today at time x and the deadline is tomorrow or future at time y, I would like to calculate the time remaining inform of a countdown timer. I have managed to get the time remaining and my problem is count down timer to show the remaining days, hours, minutes, and seconds.
The following HTML code indicates the remaining time to the deadline
<span style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>8</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>1</span> Seconds
</span>
My jQuery code:
<script>
$(function(){
var days = parseInt( $('.e-m-days').html() );
var hours = parseInt( $('.e-m-hours').html() );
var minutes = parseInt( $('.e-m-minutes').html() );
var seconds = parseInt( $('.e-m-seconds').html() );
var minutesWrap = 0;
var hoursWrap = 0;
var daysWrap;
var hoursRem = hours;
var timer = seconds;
var counter =seconds;
function countOrdersRemainingTime(){
var id = setTimeout(countOrdersRemainingTime, 1000);
if(timer < 0){
minutesWrap ++;
timer = 59;
}
var minRem = minutes - minutesWrap;
if( minRem == -1 ){
hoursWrap + 1;
minRem = 59;
var hoursRem = hours - 1;
}
if(days == 0 && hours == 0 && minutes == 0 && seconds == 0){
clearTimeout(id);
}
$('.e-m-seconds').html(timer);
$('.e-m-minutes').html(minRem);
$('.e-m-hours').html(hoursRem);
timer --;
}
countOrdersRemainingTime();
});
</script>
The key thing is to create a count down timer that counts until the deadline is reached, i.e until the number of days, hours, minutes, and seconds becomes zero. I have tried for hours with no success :(.
Consider the following example.
$(function() {
function getCounterData(obj) {
var days = parseInt($('.e-m-days', obj).text());
var hours = parseInt($('.e-m-hours', obj).text());
var minutes = parseInt($('.e-m-minutes', obj).text());
var seconds = parseInt($('.e-m-seconds', obj).text());
return seconds + (minutes * 60) + (hours * 3600) + (days * 3600 * 24);
}
function setCounterData(s, obj) {
var days = Math.floor(s / (3600 * 24));
var hours = Math.floor((s % (60 * 60 * 24)) / (3600));
var minutes = Math.floor((s % (60 * 60)) / 60);
var seconds = Math.floor(s % 60);
console.log(days, hours, minutes, seconds);
$('.e-m-days', obj).html(days);
$('.e-m-hours', obj).html(hours);
$('.e-m-minutes', obj).html(minutes);
$('.e-m-seconds', obj).html(seconds);
}
var count = getCounterData($(".counter"));
var timer = setInterval(function() {
count--;
if (count == 0) {
clearInterval(timer);
return;
}
setCounterData(count, $(".counter"));
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter" style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>8</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>1</span> Seconds
</div>
Based on: https://www.w3schools.com/howto/howto_js_countdown.asp
I believe this is what you're looking for. I've added comments to show exactly what's happening. Please let me know if anything isn't clear. I just picked a random date as a target date, but you can change it to anything you want :)
$(document).ready(function() {
const days = $(".e-m-days");
const hours = $(".e-m-hours");
const minutes = $(".e-m-minutes");
const seconds = $(".e-m-seconds");
const targetDate = new Date('May 17, 2020 03:24:00');
function convertMillis(milliseconds, format) {
var days, hours, minutes, seconds, total_hours, total_minutes, total_seconds;
total_seconds = parseInt(Math.floor(milliseconds / 1000));
total_minutes = parseInt(Math.floor(total_seconds / 60));
total_hours = parseInt(Math.floor(total_minutes / 60));
days = parseInt(Math.floor(total_hours / 24));
seconds = parseInt(total_seconds % 60);
minutes = parseInt(total_minutes % 60);
hours = parseInt(total_hours % 24);
switch(format) {
case 's':
return total_seconds;
case 'm':
return total_minutes;
case 'h':
return total_hours;
case 'd':
return days;
default:
return { d: days, h: hours, m: minutes, s: seconds };
}
};
window.setInterval( function()
{
// Where we check if 'now' is greater than the target date
var date = Date.now();
if (date > targetDate)
{
// Where we break
console.log("Expired");
clearInterval();
} else
{
// Where we set values
var millis = targetDate - date;
var millisObject = convertMillis(millis);
// Display values in HTML
days.text(millisObject.d);
hours.text(millisObject.h);
minutes.text(millisObject.m);
seconds.text(millisObject.s);
};
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>0</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>0</span> Seconds
</span>
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>
How can i add the exact time like "19:30" to the counter and still show "Tomorrow", "Today" and "Expired" messages?
Because when i add "19:30:00" the counter is not accurate.
When i use "Math.floor" instead of "Math.ceil" the counter is accurate but the messages not showen at the time they should.
<!DOCTYPE HTML>
<html>
<head>
<style>
p {
text-align: center;
font-size: 60px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Dec 18, 2017 19:30: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.ceil(distance / (1000 * 60 * 60 * 24));
var hours = Math.ceil((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.ceil((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.ceil((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
console.log(days);
if (days === 1) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TOMORROW";
}
if (days === 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TODAY";
}
if (days < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
This should work
// Set the date we're counting down to
var countDownDate = new Date("Dec 3, 2017 19:30:00");
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
// Find the distance between now an the count down date
var distance = countDownDate.getTime() - now.getTime();
// 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
console.log(days);
var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
if (tomorrow.getFullYear() == countDownDate.getFullYear() && tomorrow.getMonth() == countDownDate.getMonth() && tomorrow.getDate() == countDownDate.getDate()) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TOMORROW";
} else if (now.getFullYear() == countDownDate.getFullYear() && now.getMonth() == countDownDate.getMonth() && now.getDate() == countDownDate.getDate()) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TODAY";
} else if (countDownDate.getTime() < now.getTime()) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
p {
text-align: center;
font-size: 60px;
}
<p id="demo"></p>