Time interval not resetting, however same code runs fine on another site - javascript

My friend has given me files of his website to clone and make my own version, everything works as intended except for this time interval function. It works perfectly fine on my friends website, however on mine I found the countdown goes to zero, refreshes the page and doesn't reset, causing the page to reload constantly
var x = setInterval(function() {
var thing = parseInt($('#quest_reset').val());
thing = thing * 1000;
var now = new Date().getTime();
var distance = thing - 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("hours").innerHTML = hours
document.getElementById("minutes").innerHTML = minutes
document.getElementById("seconds").innerHTML = seconds
if (distance < 0) {
console.log(distance)
clearInterval(x);
document.getElementById("hours").innerHTML = 0
document.getElementById("minutes").innerHTML = 0
document.getElementById("seconds").innerHTML = 0
location.reload();
}
}, 1000);
The original value of thing is 1628380822, which would mean the value of #quest_reset would also be 1628380822 I found the value of now is much larger than thing
How come this works fine on my friends website but not on mine?

I guess that you code is fine, but here is my version. Instead of all the calculations you can use the Date object.
Here I define a future date by creating a new date and add 20 seconds to it. This is the timestamp that you compare against. This could also be a fixed number -- like the thing that you refer to.
In the function checktime the ´diffdate´ is the difference between the future date and now. If diff is less then 0 diffdate is set to 0, the interval is cleared and you can then reload or whatever. As the last thing (instead of repeating the same code) in the function the hour, minutes and seconds are set in the HTML elements.
All timestamps in the browser will start at Jan 01 1970 00:00:00 GMT. Try to console.log(new Date(0)). Your thing is a number of milliseconds -- probably the difference or a period defined by something. That is why thing is mush smaller than new Date().getTime() because that is the number of milliseconds from Jan 01 1970 and until now.
var h = document.getElementById("hours");
var m = document.getElementById("minutes");
var s = document.getElementById("seconds");
var futuredate = new Date();
futuredate.setSeconds(futuredate.getSeconds() + 20);
const checktime = function() {
let now = new Date();
let diffdate = new Date(futuredate - now);
let zero = new Date(0);
if (diffdate.getTime() < 0) {
diffdate = new Date(0);
clearInterval(x);
console.log('reload!');
}
h.innerText = diffdate.getHours() - zero.getHours();
m.innerText = diffdate.getMinutes() - zero.getMinutes();
s.innerText = diffdate.getSeconds() - zero.getSeconds();
};
var x = setInterval(checktime, 1000);
<div>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
</div>

Related

Timer every hour but starting from 1 minute

I would like to create a countdown timer for my resource. An example for this I took from Quasimodo's clone answer of this page.
From the code, I took some elements, since I only need minutes and seconds. And I don't need a 30 minute mark.
The code works great, but unlike the author of the question, I need the start to start and end at 1 minute of the next hour.
The changes that I made did not lead to the desired result:
secsRemaining = 3600 - (time.getUTCMinutes()+1)%60 * 60 - time.getUTCSeconds(),
and
mins = (Math.floor(secsRemaining / 60)+60),
This gave a result, but not the one that is needed. When the time on the clock becomes 00 minutes, then the code becomes 60 minutes and 00+ seconds. I need, for example, at 14:00:59 the timer has the values ​​00:01, and when 14:01:01 the timer has the values ​​59:59.
Please let me know how it can be changed to achieve the desired result. Perhaps you have a link to solutions. I couldn't find it on the Internet.
Code I am using:
var byId = document.getElementById.bind(document);
function updateTime() {
var time = new Date(),
secsRemaining = 3600 - (time.getUTCMinutes()) % 60 * 60 - time.getUTCSeconds(),
mins = (Math.floor(secsRemaining / 60)),
secs = secsRemaining % 60;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
setTimeout(updateTime, 1000 - (new Date()).getUTCMilliseconds()).toLocaleString();
}
updateTime();
<div>Time left before update: <span id="min-part"></span>:<span id="sec-part"></span></div>
Here is how I would do it
Generating a date at the next hour and 1 minutes
Calculating the number of millisecond between the current date and the next date
Display the time remaining
const minutes = document.getElementById('minutes')
const seconds = document.getElementById('seconds')
setInterval(() => {
const now = new Date()
const nextHours = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 1)
const nbMilisec = (nextHours - now)
const nbMinutes = parseInt((nbMilisec / 1000 / 60) % 60)
const nbSeconds = parseInt((nbMilisec / 1000) % 60)
minutes.innerHTML = String(nbMinutes).padStart(2, '0')
seconds.innerHTML = String(nbSeconds).padStart(2, '0')
}, 1000)
<div id="time">
Time left before update : <span id="minutes"></span> : <span id="seconds"></span>
</div>
If I understood well your needs, this should be the code you need:
var byId = document.getElementById.bind(document);
function updateTime()
{
var
time = new Date(),
// You need an hour of countdown, so 30 becomes 60
secsRemaining = 3600 - (time.getUTCMinutes()+60)%60 * 60 - time.getUTCSeconds(),
// integer division
// you want the timer to "end" at minute 1, so add 1 minute to the minutes counter
mins = (Math.floor(secsRemaining / 60) + 1) % 60,
secs = secsRemaining % 60
;
byId('min-total').textContent = secsRemaining;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
// let's be sophisticated and get a fresh time object
// to calculate the next seconds shift of the clock
setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
}
updateTime();

How do I get Date but Manually enter time to then calculate countdown expiry?

I am I want to select a and back date a time, add 8 hours to the timer and start a countdown based on the calculated remaining time. Basic Webpage in HTML/CSS/JS to monitor curing time of a product. I need to set the timer of 8 hours after I have mixed the resin which can be a random start time.
I can hard code the deadline time from the newDate and getTime but I'm struggling to understand how to manually enter the time and to calculate then deadline time. The actual calculation is easy enough for variable t to then start the countdown, it is the backdated start time then adding 8 hours that stumps me.
<script>
var deadline = new Date("March 25, 2021 12:34:00").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var t = deadline - now;
var hours = Math.floor((t%(1000 * 60 * 60 * 24))/(1000 * 60 * 60));
var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((t % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
if (t < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Rotate";
}
}, 1000);
</script>

How to make double "if" condition in a countdown

I have the following javascript code:
function t5am() {
// Set the date we're counting down to
// Year, Month ( 0 for January ), Day, Hour, Minute, Second, , Milliseconds
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::: 5:00 AM ::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// (AAAA,MM,DD,HH,mm,S));
var countDownDate = new Date(Date.UTC(2020,05,29,12,00,00));
// 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
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
// 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"
for (const ele of document.getElementsByClassName("t5am")){
ele.innerHTML = (days + "<span>d</span> " + hours + "<span>h</span> "
+ minutes + "<span>m</span> " + seconds + "<span>s</span><br />")
}
// If the count down is over, write some text
if (distance < 0) {
for (const ele of document.getElementsByClassName("t5am")) {
ele.innerHTML = "<p class='live-text'>Live</p> ";
}
if (distance + 7200000 < 0){
ele.innerHTML = "Ended";
}
}
}, 1000);
}
t5am()
It is a counter that works fine for me, but now I want to do a double "if" function.
When the counter reaches zero, then it shows "Started".
I need that in addition to that, after 2 hours after "Started", it shows "Ended"
How can I do it?
This is how you can do this:
Just need add two more hours to your current time which i have done below and then check if distance + twoHours < 0 to show 'Ended' Message
Also, you have to clearInterval(x) as well i will leave that for you to clear when you want after the condition have been met and it is ended.
Remember: Its NOT ideal to use setTimeout for this because if the user leave the page and come page the setTimeout funtion will start from 2 hours again which is not ideal in your case you want to stop it exactly after 2 hours to when its was started which will be in real time regardless of user staying on the browser / screen or not.
Just to make some correction on using innerHTML as well. Its is not rec-emended to user innerHTML at all. I have used textContent which is exactly the same.
InnerHTML is not rec-emended officially by javascript MDN . You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML why its not good to use innerHTML to change text in elements.
Recreated Demo: https://jsfiddle.net/bv0odyqr/1/
Try this code and should work just fine.
function t5am() {
// Set the date we're counting down to
// Year, Month ( 0 for January ), Day, Hour, Minute, Second, , Milliseconds
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::: #1 ::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// (AAAA,MM,DD,HH,mm,S));
var countDownDate = new Date(Date.UTC(2020, 05, 27, 20, 20, 0));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
const twoHours = new Date();
twoHours.setHours(twoHours.getHours() + 2);
var two = twoHours.getTime()
// Find the distance between now an the count down date
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
//Results div
var result = document.getElementsByClassName("t5am")[0];
// 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.getElementsByClassName("t5am")[0].textContent = days + "<span>d</span> " + hours + "<span>h</span> " +
minutes + "<span>m</span> " + seconds + "<span>s</span><br />";
// If the count down is over, write some text
if (distance < 0) {
result.textContent = "Started";
} else if (distance + twoHours < 0) {
result.textContent = "Ended";
}
}, 1000);
}
t5am()
<div class="t5am"></div>

Countdown Timer - Timezone Issues

I was following this tutorial: https://www.w3schools.com/howto/howto_js_countdown.asp
And everything works except for timezones, I want it to show the same time on every device, no matter the timezone, in UTC. How would I go about this?
If someone in a timezone was ahead of me, they would see a different time (because they are an hour ahead, so the countdown would end at a different time. It would end for them an hour ahead of when it ends for me, I want the same time on the timer to be shown everywhere
Code (Edited):
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
function getUTCNow() {
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
// Set the date we're counting down to
//var countDownDate = new Date("Sep 15, 2018 15:00:00").getTime();
var countDownDate = new Date("Sep 7, 2018 20:00:00");
var countDD = convertDateToUTC(countDownDate);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
var nowUTC = now.getUTCTime();
// Find the distance between now and the count down date
var distance = countDD.getTime() - nowUTC.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);
// Display the result in the element with id="timer"
document.getElementById("timer").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("timer").innerHTML = "RELEASED!";
}
}, 1000);
<div id="timer"></div>

How can I add a specific time zone to this code?

I have this code but the only thing is I can't figure out how to add a time zone to it. I have the date set but no time zone. How would I add it to the countDownDate?
// Set the date we're counting down to
var countDownDate = new Date("May 8, 2018 16: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;
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 = "<p>" + hours + ":" + minutes + ":" + seconds + "</p>";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "expired";
}
}, 1000);
<div id="countdown"></div>
New Date() objects are in the system's local timezone. If you want to set a timezone directly, one way to do so would be to create your time in UTC time and then add the offset of the local timezone you are looking for.
let dateUTC = new Date(Date.UTC('...'))
let offset = (60*60*1000) * 4 // EST would be UTC+4, hence 4 * the number of ms in an hour.
let dateEST = dateUTC+offset
An alternative would be to just use a date string, with the timezone specified:
let dateEST = new Date('2018-05-08T14:45:00+0400') //The '+0400' is the '+4' for EST.
EDIT: Just tried adding "GMT" to my date variable and it works. Didn't think that would.
So I now have:
var countDownDate = new Date("May 8, 2018 16:00:00 GMT").getTime();
And I set the time +/- from my time zone and it works.

Categories

Resources