JavaScript and content change after load - countdown timer from date - javascript

I'm trying to have a simple countdown timer that converts a time given on a page to a countdown.
It works, but my current issue is how the normal date is shown and then later it's parsed by the JavaScript. I want it parsed by JS right away so a user doesn't see it flicking between the date and the countdown timer.
It converts this to the countdown:
<span class="countdown">12/10/20 13:10:00</span>
This is the code:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).text();
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).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"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
}, 1000);
});
}
What I am asking for, is suggestions on how to get around this problem. Is the only way to have it loaded before the HTML or what? I'm confused on the best practices for this. Everywhere keeps telling me to defer JavaScript loading...but what about stuff like this that changes the content?
In cases like this, is it a good idea to have a "core" file for content-changing stuff that loads right away, then the rest after the content or what?

The problems comes from setInterval not executing automatically , which is normal. Here's a work around it:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).text();
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
var counterFunction = 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"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
return counterFunction;
}
// Update the count down every 1 second
var x = setInterval(counterFunction(), 1000);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="countdown">12/10/20 13:10:00</span>

I suggest to put the date in data-date attr, like this:
<span data-date="12/10/20 13:10:00" class="countdown"></span>
than the script:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).attr("data-date");
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).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"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
}, 1000);
});
}
https://jsfiddle.net/750o1neh/

Related

I have a countdown, but it seems to be affected by local timezone, how do I transform this into a universal timezone countdown?

// Set the date we're counting down to
var countDownDate = new Date("July 26, 2022 19:00:00").getTime();
// Update the count down every 1 second
var countdownfunction = 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("countdown").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(countdownfunction);
document.getElementById("countdown").innerHTML = "Refresh the page! Ctrl+F5";
}
}, 1000);
This is my current javascript, but it shows a differnt end date regarding on which timezone their computer is currently set to, is there an easy way to fix this?

Countdown timer - Hide variables as they expire

looking for help with a countdown timer I have to reveal a container the page at a specific time. I'd like the "days" "hours" "minutes" to disappear when they reach zero.
Can anyone help?
<h3 id="demo"></h3>
<script>
// Set the date we're counting down to
var countDownDate = new Date("1/21/2022 11: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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + " day " + hours + " hours " + minutes + " min " + seconds + " sec ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Reserve Tickets";
}
}, 1000);
</script>
Update variables only if distance > 0
<h3 id="demo"></h3>
<script>
// Set the date we're counting down to
var countDownDate = new Date("1/21/2022 11:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
let now = new Date().getTime();
// Find the distance between now and the count down date
let distance = countDownDate - now;
// If the count down is over, write some text
if (distance >= 0) {
// Time calculations for days, hours, minutes and seconds
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + " day " + hours + " hours " + minutes + " min " + seconds + " sec ";
} else {
clearInterval(x);
document.getElementById("demo").innerHTML = "Reserve Tickets";
}
}, 1000);
</script>

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>

NaN on Javascript countdown timer in Internet Explorer

I'm using the following JavaScript for a countdown timer and it has been working great in most browsers, I've just double checked Internet Explorer however and I am getting 'NaN' displayed in place of each number.
Can anyone help to explain where this goes wrong in IE not seeing the individual variables as a number?
// Set the date we're counting down to
var countDownDate = new Date("2018-05-25 12:00: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);
if (days.toString().length < 2) {
days = "0" + days;
}
if (hours.toString().length < 2) {
hours = "0" + hours;
}
if (minutes.toString().length < 2) {
minutes = "0" + minutes;
}
if (seconds.toString().length < 2) {
seconds = "0" + seconds;
}
// Display the result in the element with id="countdown"
document.getElementById("countdown").innerHTML = days + " : " + hours + " : " +
minutes + " : " + seconds;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>
MDN discourages the use of a string in the date constructor because not all browsers implement this the same way.
If you do want to use date strings, I would recommend using a third party library like momentjs to parse these strings to make sure this works in every browser.
Just normalise the date and time
function getNormalisedDatetime(dString) { // yyyy-mm-dd hh:mm:ss
var parts = dString.split(" ");
var dParts = parts[0].split("-");
var tParts = parts[1].split(":");
return new Date(dParts[0],dParts[1]-1,dParts[2],tParts[0],tParts[1],tParts[2]);
}
function pad(num) {
return ("0"+num).slice(-2);
}
// Set the date we're counting down to
var countDownDate = getNormalisedDatetime("2018-05-25 12:00: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);
// Display the result in the element with id="countdown"
document.getElementById("countdown").innerHTML = "" + pad(days) + " : " + pad(hours) + " : " +
pad(minutes) + " : " + pad(seconds);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>

JavaScript timer not working on multiple instance

Below is a result of a loop and I want to run timer to count up to the set time for each of the loop result.
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
The timer script:
$(document).ready(function(){
$('[data-time]').each(function() {
console.log($(this))
var $this = $(this),
finalTime = $(this).data('time'),
url = $(this).data('url')
// Set the date we're counting down to
var countDownDate = new Date(finalTime).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);
// Display the result in an element with id="demo"
document.getElementById("time").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("time").innerHTML = "EXPIRED";
}
}, 1000);
})
})
So am using Laravel and jQuery to run the timer.
I want assistance with the code because it is not working.
The trick is to "save" you intervals in an array.
If you do not do it, it gets overwritten on each loop iteration.
Then, to refer to the right span element, you have to get the iteration index for later use in an .eq() method.
You can't use an id in a loop, since it has to be unique.
Have a look at comments within the code.
$(document).ready(function(){
// an arrary to store the intervals created.
var timerArray = [];
$('[data-time]').each(function(index) {
console.log($(this).data("time"));
var finalTime = $(this).data('time');
// Set the date we're counting down to
var countDownDate = new Date(finalTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// this Index will be used to refer to the right span.
var thisIndex = index;
console.log("interval "+thisIndex);
// 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);
// Leading zeros...
if(hours<10){hours="0"+hours}
if(minutes<10){minutes="0"+minutes}
if(seconds<10){seconds="0"+seconds}
// Display the result in an element with id="demo"
$('[data-time]').eq(thisIndex).html( days + "d " + hours + "h " + minutes + "m " + seconds + "s " );
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(timerArray[thisIndex]);
$('[data-time]').eq(thisIndex).html("EXPIRED");
}
}, 1000);
// Place this timer in an array... So it won't be overwritten.
timerArray.push(x);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-time="07/08/2017 12:30:00"></span><br>
<br>
<span data-time="07/10/2017 19:50:30"></span><br>
<br>
<span data-time="07/12/2017 5:24:24"></span><br>
<br>
Run the snippet in "full page" or look at this CodePen.

Categories