How to add event through time? - javascript

I have a countup function. I want some event happen on specific time for example: I want to add a class on element if the time has already crossed 10 days or 10 hours.
You can check the thing here:
https://stackblitz.com/edit/web-platform-cysyfo?file=index.html
//Here is my countup code:
function updateTimer() {
// yyyy-MM-dd HH:mm:ss
past = Date.parse("2023-01-18 06:00:00");
now = new Date();
diff = now - past;
years = Math.floor(diff / (1000 * 60 * 60 * 24 * 30 * 12));
months = Math.floor(diff / (1000 * 60 * 60 * 24 * 30));
days = Math.floor(diff / (1000 * 60 * 60 * 24));
hours = Math.floor(diff / (1000 * 60 * 60));
mins = Math.floor(diff / (1000 * 60));
secs = Math.floor(diff / 1000);
y = years;
M = months - years * 12;
d = days - months * 30;
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
document.getElementById("timer")
.innerHTML =
'<div><span>since: 19.01.2023</span></div><br>' +
'<div class="number">' + M + '<span>Months</span></div>' +
'<div class="number">' + d + '<span>Days</span></div>' +
'<div class="number">' + h + '<span>Hours</span></div>' +
'<div class="number">' + m + '<span>Minutes</span></div>' +
'<div class="number">' + s + '<span>Seconds</span></div>';
}
setInterval('updateTimer()', 1000);
//And this is what I have tried:
let Hello = document.querySelector('.hello')
let Timer = document.getElementById('timer')
if (timer.innerHTML == '<div class="number">10<span>Days</span></div>') {
Hello.classList.add("Level-10");
} else {
Hello.classList.remove("Level-10");
}

Why don't you simply add the class in the innerHtml instead of comparing the string?
<div class=" ${
d === 10 ? '' : ''
}">
// if (timer.innerHTML == '<div class="number">10<span>Days</span>
PS: setInterval(updateTimer, 1000);
https://stackblitz.com/edit/web-platform-kxeyt3?file=script.js

Related

(Django - Javascript) Timer javascript and datetime python variable in html template

I've found a timer countdown in javascript online and it works fine...
I have to pass python variable to it but, although the result is correct, the countdown doesn't run, it shows the correct remaining time but doesn't continue to decrease (at least I refresh the page)...
These are my piece of codes:
views.py
import datetime
auction = Auction.objects.get(id=id)
endDateFormat = auction.endDate.strftime("%Y-%m-%dT%H:%M:%S")
startDateFormat = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
template.html
<script>
// Set the date we're counting down to
var countDownDate = new Date("{{endDateFormat}}").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date("{{startDateFormat}}").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);
</script>
Thanks to everyone!
Try this! Given a view:
def timer_page_view(request):
auction = Auction.objects.last()
context = {
'start_date': auction.start_date.strftime("%Y-%m-%dT%H:%M:%S"),
'end_date': auction.end_date.strftime("%Y-%m-%dT%H:%M:%S"),
}
return render(request, 'timer_page.html', context=context)
Your timer_page.html template could look like this:
<body>
<p>start date is {{ start_date }}</p>
<p>start date is {{ end_date }}</p>
<div id='demo'>time difference</div>
</body>
<script>
// Set the date we are counting to
var countDownDate = new Date('{{ end_date }}');
// Set the date we are counting from
var countFromDate = new Date("{{ start_date }}");
// Set inital distance in seconds
var distance = (countDownDate.getTime() - countFromDate.getTime()) / 1000;
// Set initial time difference in the DOM
var days = Math.floor((distance / (60 * 60 * 24)));
var hours = Math.floor((distance - (days * (60 * 60 * 24))) / (60 * 60));
var minutes = Math.floor((distance - ((days * (60 * 60 * 24)) + (hours * (60 * 60)))) / 60);
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + ' ' + hours + ' ' + minutes + ' ' + seconds;
// Timer
let active = true;
startTimer = () => {
if (active) {
var timer = document.getElementById("demo").innerHTML;
let nums = timer.split(" ").map(num => parseInt(num))
let day = nums[0];
let hour = nums[1];
let min = nums[2];
let sec = nums[3];
if (sec == 0) {
if (min == 0) {
hour--;
min = 59;
if (hour == 0){
day--;
hour = 23;
}
if (hour < 10) hour = "0" + hour;
} else {
min--;
}
if (min < 10) min = "0" + min;
sec = 59;
} else {
sec--;
console.log(sec)
if (sec < 10) sec = "0" + sec;
}
document.getElementById("demo").innerHTML = day + ' ' + hour + ' ' + min + ' ' + sec;
setTimeout(startTimer, 1000);
}
}
startTimer();
</script>
The timer would start immediately here, but you can play around with that to your liking.

Get custom attribute value for countdown timer (timer shows NaN)

Can't assign the end date to the variable for the timer to work. As a result, I get NaN
Can you please tell me what is the mistake?
var countDownDate = new Date($("countdown").data("datetime")).getTime();
function ctd() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
countdown = document.getElementsByClassName("countdown");
countdown[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
countdown.innerHTML = "Item expired!";
}
}
ctd();
var x = setInterval(ctd, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<time class="countdown" datetime="2020-11-22T16:20:22+00:00"></time>
You repeat some of the time calculations every second, better use some const instead:
const eCountDown = document.querySelector('.countdown')
, one_Sec = 1000
, one_Min = one_Sec * 60
, one_Hour = one_Min * 60
, one_Day = one_Hour * 24
;
var countDownDate = new Date(eCountDown.dateTime).getTime()
;
function ctd()
{
let now = new Date().getTime()
, distance = countDownDate - now
, days = Math.floor(distance / one_Day)
, hours = Math.floor((distance % one_Day) / one_Hour)
, minutes = Math.floor((distance % one_Hour) / one_Min)
, seconds = Math.floor((distance % one_Min) / one_Sec)
;
eCountDown.textContent = days + 'd '
+ hours + 'h '
+ minutes + 'm '
+ seconds + 's '
;
if (distance < 0)
{
clearInterval(timerIntv)
countdown.textContent = 'Item expired!'
}
}
ctd()
var timerIntv = setInterval(ctd, 1000)
<time class="countdown" datetime="2020-11-22T16:20:22+00:00"></time>
You need to use .countdown to get a class. You were missing the dot (.)
Also you should use attr or prop and not data. You can use data if you change your html property to data-datetime.
When in doubt, always console.log(countDownDate) to see what you get first.
var countDownDate = new Date($(".countdown").attr("datetime"));
function ctd() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
countdown = document.getElementsByClassName("countdown");
countdown[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
countdown.innerHTML = "Item expired!";
}
}
ctd();
var x = setInterval(ctd, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<time class="countdown" datetime="2020-11-22T16:20:22+00:00"></time>

JavaScript - Reset timer after < 0

var start = new Date;
start.setHours(14, 0, 0); //2pm
var x = setInterval(function() {
var now = new Date().getTime();
var distance = start - now;
//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);
document.getElementById("countdown").innerHTML = "Order before " + /*days + "d " +*/ hours + "h "
+ minutes + "m " + seconds + "s " + " for delivery tomorrow";
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "EXPIRED";
}
}, 1000);
At the moment i have this JS which after 2pm it says 'Expired' but i no longer want that and wasnt sure how to just reset the timer and make it start counting towards tomorrows 2pm
var d = new Date();
var local_date = new Date( Date.UTC( d.getFullYear(), d.getMonth(), d.getDate(), 14,0) );
var now = new Date().getTime();
var distance = local_date - now;
Change your codes as given above.
set your local_date variable with local date and time.
local_date is also a time.
You may also ignore UTC as per your requirements.

JavaScript timer stuck when adding PHP script to footer

I'm trying to convert the 0 in stock text on my website (held within a <p> tag) to a countdown timer, once the stock level hits 0. So I've added this code to the footer - however it seems to just stick, and not count down at all. It also takes a few seconds to replace the 0 in stock text - can I make this quicker/instant? Here's the code so far:
// Set the count down date
var countDownDate = new Date("Feb 21, 2021 15:26:00").getTime();
// Update the count every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// 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 if stock = 0
list = document.getElementsByClassName("stock in-stock");
if (list[0].innerHTML == "0 in stock") {
list[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
// If the count down is finished, write text
if (distance < 0) {
clearInterval(x);
list = document.getElementsByClassName("stock in-stock");
list[0].innerHTML = "Item expired!";
}
}, 1000);
<p class="stock in-stock">1 in stock</p>
You were trying to populate the P with new data and somehow trying to read out the old data, I've just separated that into 2 spans so you can work with each one individually and updated your JS to reflect the new structure.
To speed up the first call, extract the function:
Please note that we're treating "stock" and "countdown" as 2 different things now.
// Set the count down date
var countDownDate = new Date("Feb 21, 2021 15:26:00").getTime();
function ctd() {
// Get today's date and time
var now = new Date().getTime();
// 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);
//console.log(days + " " + hours + " " + minutes + " " + seconds);
// Display the result if stock = 0
countdown = document.getElementsByClassName("countdown");
stock = document.getElementsByClassName("stock-level");
if (stock[0].innerHTML == "1") {
countdown[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
// If the count down is finished, write text
if (distance < 0) {
clearInterval(x);
countdown.innerHTML = "Item expired!";
}
}
ctd(); // run now
// Update the count every 1 second
var x = setInterval(ctd, 1000);
<p class="stock-level" style="display:none">1</p>
<p class="countdown"></p>
I got it to work. Here's the code:
<script>
//Set the count down date
var countDownDate = new Date("Feb 20, 2019 18:26:00").getTime();
var startTimer=false;
list = document.getElementsByClassName("stock in-stock");
if(list[0].innerHTML=='1 in stock') {
startTimer=true;
}
//Check if 1 left
list = document.getElementsByClassName("stock in-stock");
//Update the count every 1 second
var x = setInterval(function() {
//Get today's date and time
var now = new Date().getTime();
//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);
//Update the counter
if(startTimer) {
list[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
//If the count down is finished, write text
if (distance < 0) {
clearInterval(x);
list = document.getElementsByClassName("stock in-stock");
list[0].innerHTML = "Item expired!";
}
}, 1000);
</script>

How to convert 24 hours time format to 12 hours with AM or PM using javascript

I have requirement if countdown timer in my project so I am using code for that but that code showing 24 hrs format but i want 12 hours format with AM or PM should show instead of 13,14,15 I want hours should come like this
1:00 PM,2:00 PM,3:00 PM.any idea how to do this ?
<p id="check_time"></p>
<p id="check_hours"></p>
<script>
var countDownDate = new Date("may 17, 2018 01:37:25").getTime(); //this the which i have to count for difference
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
document.getElementById("check_hours").innerHTML = hours;
document.getElementById("check_time").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Try the following:
var countDownDate = new Date("june 17, 2018 01:37:25").getTime(); //this the which i have to count for difference
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
var n = new Date();
var h = n.getHours() < 10 ? '0' + n.getHours() : n.getHours();
var min = n.getMinutes() < 10 ? '0' + n.getMinutes() : n.getMinutes();
var sec = h < 10 ? '0' + n.getSeconds() : n.getSeconds();
var time = n.getHours() + ':' + min + ':' + sec;
document.getElementById("check_hours").innerHTML = tConvert(time);
document.getElementById("check_time").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
<p id="check_time"></p>
<p id="check_hours"></p>
<p id="demo"></p>

Categories