I have a project where I need to do a countdown timer, However no function can be used. I know that this can be done with a setInterval, however, most of the documentation I have found shows a function being used in conjunction. W3schools has a great example, however, it used a function. I know how I would do it with
I have already written some code, and was able to display the minutes and seconds, however, cannot get it to actually count down. is there a way to do this without a function?
const timeSpan = document.getElementById('timer');
// Get Time Now
var timeMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeMinutes * 60 * 1000);
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
timeSpan.innerHTML = minutes + 's' + seconds;
This shows the minutes and seconds, but without the setInterval or setTimeOut it wont count down like a normal countdown timer. For the project it needs to count down from ten minutes and at the end alert the user that is is expired and that they will need to refresh the page.
You need to move some things out of the function as you are resetting the timer on every interval. You should avoid storing your times as Date objects as well since you only need the timestamps.
const timeSpan = document.getElementById('timer');
const mins = 10;
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;
setInterval(() => {
var currentTime = new Date().getTime();
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
timeSpan.innerHTML = minutes + 's' + seconds;
}, 500)
<span id=timer></span>
<script>
var timer = (mins) => {
const timeSpan = document.getElementById('timer');
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;
setInterval(() => {
var currentTime = new Date().getTime();
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
timeSpan.innerHTML = minutes + ' min. ' + seconds + ' s.';
if (minutes <=0 && seconds <=0) {
alert('Time is over');
return false;
}
}, 1000);
}
timer(10);
</script>
<span id="timer"></span>
Related
I am writing a HTML embed that displays a countdown for wednesday at 20:30 EST. Everytime it hits that date and time it will set the date to the following wednesday and start counting down the date. The issue is that I am using the .getTime() function to grab the current time. That function will grab the local computer time and I need the script to compare to Eastern Standard Time instead of the local time so the countdown is the same regardless where in the world you are.
Code with .getTime()
<script>
var countDownDate = new Date("Jan 25, 2023 20:30:00").getTime();
var x = setInterval(countdown, 1000);
function countdown(){
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("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("mins").innerHTML = minutes;
document.getElementById("secs").innerHTML = seconds;
if (distance < 0) {
resetCountdown();
}
}
function resetCountdown(){
clearInterval(x);
var nextWednesday = new Date();
nextWednesday.setDate(nextWednesday.getDate() + (3 + 7 - nextWednesday.getDay()) % 7);
nextWednesday.setHours(20);
nextWednesday.setMinutes(30);
countDownDate = nextWednesday.getTime();
x = setInterval(countdown, 1000);
}
</script>
I tried to use .getUTCDate() and similar functions and wasn't having any luck.
function resetCountdown(){
clearInterval(x);
var nextWednesday = new Date();
nextWednesday.setUTCDate(nextWednesday.getUTCDate() + (3 + 7 - nextWednesday.getUTCDay()) % 7);
nextWednesday.setUTCHours(20);
nextWednesday.setUTCMinutes(30);
countDownDate = nextWednesday.getTime();
x = setInterval(countdown, 1000);
}
i want to make count timer from 00:00:00, the count start if "div id = data" is filled with "const date" and the time increase until the code receive stop trigger. how i can achieve that?
here is my current code :
<div id="data"></div>
<p id="demo"></p>
<script>
const api_url = 'json.php'
async function okejson() {
const resp = await fetch(api_url);
const dat = await resp.json();
const awal = (dat[0])
const date = awal.tanggal
document.getElementById("data").innerHtml = date
var distance = 0;
var x = setInterval(function() {
distance +=1;
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("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
}, 1000); }
</script>
Using setInterval will not yeild accurate results. It is acceptable for short periods and non critical applications. If it may take hours you should consider using system clock. However here is a constructor which you can use to generate an object which has a start (and also stop and reset) method on it. The start method accepts a callback function which it will call each second and passes an object with days, hours, minutes, and seconds properties. You can use it to do whatever you want.
function Timer() {
this.value = 0
this.updateCb = null
this.interval = null
function getTime() {
console.log(this.value)
var seconds = this.value % 60
var minutes = Math.floor(this.value / 60)
var hours = Math.floor(this.value / 3600)
var days = Math.floor(this.value / (3600 * 24))
return { days: days, hours: hours % 24, minutes: minutes % 60, seconds }
}
this.start = function (cb) {
if (cb) this.updateCb = cb
clearInterval(this.interval)
var self = this
interval = setInterval(function () {
self.value += 1
if (self.updateCb) self.updateCb(getTime.bind(self)())
}, 1000)
}
this.stop = function () {
this.clearInterval(interval)
}
this.reset = function () {
this.value = 0
clearInterval(interval)
}
}
var timer = new Timer()
timer.start(function (time) {
console.log(time)
})
You can start the timer on click of a button or whatever other event.
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/
I'm creating a countdown and he is working. the only thing i don't find is how to have the good local time ? I think i need to change something with the date.now() but i'm not sure
TimerDecibels = () => {
return this.state.sport.clubs.map((element) => {
// Set the date we're counting down to
// Update the count down every 1 second
setInterval(() => {
// Get today's date and time
var now = Date.now();
var countDownDate = new Date(element.dateMatchStop).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 * 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"
this.setState({heures: hours});
this.setState({minutes: minutes});
this.setState({secondes: seconds});
// If the count down is over, write some text
if (distance < 0) {
return this.setState({expired: 'EXPIRED'});
}
}, 0);
});
};
I am trying to make a Countdown Timer in javascript and I wrote a code like
var countdown = function(){
setInterval(function() {
var countDownDate = new Date(document.getElementById("end_date").getAttribute("data-date")).getTime();
// data-date ex. = "2017-11-28 21:54:00"; greater than current date (now)
// 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="demo"
if(hours<10){
hours = "0"+hours;
}
if(minutes<10){
minutes = "0"+minutes;
}
if(seconds<10){
seconds = "0"+seconds;
}
var left = hours + ":"+ minutes + ":" + seconds;
console.log(left);
document.getElementById("time_left").innerHTML = left;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("time_left").innerHTML = "EXPIRED";
}
}, 1000);
}
countdown();
Counter is working fine but why I am getting difference of time upto 25 secs on different systems. Some systems shows same countdown time but, some not.
you should use your sever time and java script take the system time so when u change your system time count down will change automatically. you can also provide me your code using js fiddle or anything else...