Automatically load new HTML page at given time - javascript

I would like my homepage to change each day at a specific time (1pm).
The page has a 24hr countdown timer and when it reaches zero, I would like a new page to load and the timer starts again.
I understand how to make a page refresh after a particular time
<script>
setTimeout(function(){
window.location='Page2.html';
}, 5000);
</script>
But not how to make this happen at a particular time of the day (1pm).

You can try using a getting the current time on page load/refresh. Then calc the milliseconds until 1pm. And use that to set your setTimeout. I suggest using a library like moment to do time calculations.
Load moments in your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
In JS:
// time right now
var now = moment.now();
// set refresh hour to 1pm
var nextRefresh = moment.now().hour(13).minute(0).second(0).millisecond(0);
// check if is or after 1pm
if (now.hour >= 13) {
nextRefresh.add(1, 'days'); // add 1 day
}
setTimeout(function() {
console.log('next 1pm');
}, nextRefresh.diff(now));
And #Stoycho Trenchev is right. You will probably want to call setInterval with 86400000 ms in the setTimeout. This way, your page will refresh everyday afterwards.

You need setInterval not setTimeout and you need to calculate 24h in milliseconds :)

Here you go just a fyi JavaScript uses the browsers time so just because it's 1pm where you are it won't be 1pm where the user is.
var intervalId = window.setInterval(checkTime, 500);
function checkTime() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(h == 13 && m == 0 && s == 0) return window.location='Page2.html';
}

Ah. Something like?
<script>
function getTime() {
var date = new Date()
var time = date.getTime();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var time = {'hours': hours, 'minutes': minutes, 'seconds': seconds};
}
setInterval(function() {
var time = getTime();
if (time.hours === 13 && time.minutes === 0) {
window.location = 'Page2.html';
}
}, 500);
</script>

You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

Related

Move a div to another div on a specific time frame

Like on 7 am in the morning the code runs and moves a div to another div
here is my code
jQuery(document).ready(function(){
var tomorrow_sec = jQuery("#day").html();
jQuery("#day-dest").html(tomorrow_sec);
jQuery("#day").html(" ");
});
The code will run when you load the page.
If you want to move something, then you need to check every time you load the page what the time is, and then try to open in x milliseconds OR you need to run an interval and see if the time has been reached.
Method one:
$(function(){
var now = new Date(); // or new Date(time in milliseconds from server)
var sevenAm = new Date(now.getFullYear(), now.getMonth(), now.getDate(),7,0,0,0)
var diff = sevenAm.getTime() - now.getTime();
if (diff < 0) sevenAm.setDate(sevenAm.getDate()+1); // tomorrow
diff = sevenAm.getTime() - now.getTime();
var tId = setTimeout(function() {
var tomorrow_sec = $("#day").html();
$("#day-dest").html(tomorrow_sec);
$("#day").empty();
},diff);
});
Method 2
$(function() {
var tId = setInterval(function() {
var now = new Date();
var sevenAm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 7, 0, 0, 0)
var diff = sevenAm.getTime() - now.getTime();
if (diff < 0) sevenAm.setDate(sevenAm.getDate() + 1); // tomorrow
diff = sevenAm.getTime() - now.getTime();
if (diff <= 60000) { // within a minute - you could use Math.abs here
var tomorrow_sec = $("#day").html();
$("#day-dest").html(tomorrow_sec);
$("#day").empty();
}
}, 1000); // 30000: test every 30 seconds
});
Set an interval on page load, which will run on every 1 second. and will check the time. If the time is 07:00 am to 09:59 am then it will remove content from a div and paste into another div.
You can check the working fiddle here - Example
To test it, uncomment the line var today = new Date('01/01/2011 07:00:00'); and comment the next line var today = new Date();
var interval = setInterval(myfunction, 1000);
function myfunction() {
//var today = new Date('01/01/2011 07:00:00');
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes();
//console.log(time);
if (time >= '7:0' && time <= '9:30') {
clearInterval(interval);
var tomorrow_sec = jQuery("#day").html();
jQuery("#day-dest").html(tomorrow_sec);
jQuery("#day").html("");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="day">
content of day div
</div>
<div id="day-dest">
fghgjgh
</div>

Jquery timer with UTC offset

function getMinutesUntilNextHour() {
var now = new Date();
var hours = now.getUTCHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
// Compute time remaining per unit
var cur_hours = 23 - hours;
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
// Correct zero padding of hours if needed
if (cur_hours < 10) {
cur_hours = '0' + cur_hours;
}
// Correct zero padding of minutes if needed
if (cur_mins < 10) {
cur_mins = '0' + cur_mins;
Here’s the code for a simple 24 hour countdown timer that resets again after each 24 hours but when I add, say, 11- hours in the compute time remaining section it occasionally throws a negative time (in hours) at me depending on the current UTC time. I’d just like the 24 hour period to start from a different time /time zone. All help greatly appreciated
You might be looking at this backwards :-) Why don't you create a Date object for midnight, then subtract current time from it. This example works for the local timezone, but you could easily adapt it for UTC, or another timezone.
// We're going to use Vue to update the page each time our counter changes.
// You could also do this old style, updating the DOM directly.
// vueStore is just a global variable that will contain the current time,
// and the function to periodically update it.
var vueStore = {
now: new Date(),
countdown(){
vueStore.now = new Date();
window.setTimeout(() => {this.countdown(); }, 1000);
}
};
vueStore.countdown();
var vm = new Vue({
el: "#vueRoot",
data: { vueStore: vueStore },
computed: {
timeTilMidnight() {
var midnightTonight = new Date(this.vueStore.now.getYear(), this.vueStore.now.getMonth(), this.vueStore.now.getDay() + 1);
var timeToMidnight = midnightTonight.getTime() - this.vueStore.now.getTime();
return new Date(timeToMidnight).toLocaleTimeString([], {
timeZone: "UTC"
});
}
}
});
<script src="https://unpkg.com/vue#2.5.17/dist/vue.js"></script>
<div id="vueRoot">
<h1>{{timeTilMidnight}}</h1>
</div>

setinterval vs settimeout

How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.
I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.
1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?
2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?
This works for me
window.setInterval(function() {
var date = new Date();
if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000;
}
setTimeout(function() {
alert("It's 10am!")
}, millisTill10);
Run a timer for every minute. Show your warning if the current time falls within your allocation. The problem with this code is that it is only accurate up to a minute - not up to the second.
And running this every second is not a good practice.
setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
//Rough estimation for the time between 7.50 and 8.00 here
if (h === 7 && m >= 50)
console.log('Warning!');
}, 1000)
Now we can do more...
We can get the above routine to kick-start a timeout function which is going to be precise in the interval. It will trigger a countdown timer at the correct time and set alarm for another 24 hours.
var starter = setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
//Rough estimation for the time between 7.50 and 8.00 here
if (h === 7 && m >= 50)
setTimeout(timer24(), 1000 * 60 * 24)
}, 1000)
function timer24(){
//Warn every 10 seconds
var countdown = setInterval(function(){
console.log('Warning!');
var d = new Date();
var h = d.getHours();
if (h == 8)
clearInterval(countdown)
}, 10)
setTimeout(timer, 1000 * 60 * 24)
}
setInterval is used to repeat a callback function with a given time, setTimeout is used to run a callback after a specific amount of time. Since you need to create a counter, you can use setInterval here.
Note: If you want to display the users every sconds in 10 minutes, you may use 1000 as the interval timing value. But if you want to show every minutes in the 10 minute duration, then using 60 * 1000 as the interval timing value is better.
setInterval(function(){
var dateNow = new Date();
if(dateNow.getHours() >= 7 &&
dateNow.getMinutes >= 50 &&
dateNow.getHours < 8)
{
// if the alert box isn't displayed yet
// display it first.
// update the display.
}else{
// if the alert box is displayed
// hide it
}
}, 1000); // or 1000 * 60 for minute based display

jQuery backword Countdown from Initial HTML Value

I have a initial timer value. How can i make it so that it start counting down to 0?
I want the output to get displayed in another element
<span id="time">03:30:00</span>
<span id="output"></span>
<script type="text/javascript">
jQuery(function($){
var val = $("#time").html();
var output = "";
// count down
$("#output").html(output)
});
</script>
<script type="text/javascript">
$(function(){
var val = $("#time").html().trim();
console.log(val);
val = val.split(":");
var hr = parseInt(val[0].trim());
var mn = parseInt(val[1].trim());
var sc = parseInt(val[2].trim());
console.log(val);
var timer = setInterval(function(){
if(hr==0 && mn==0 && sc==0){
clearInterval(timer);
return;
}
if(sc==0){
sc=60;
mn--;
}
if(mn==0 && sc==0){
mn=60;
hr--;
}
sc--;
$("#output").html(hr+":"+mn+":"+sc);
},10);
});
</script>
This is not the correct answer but rather a best practise
You should use the new time element instead
<time datetime="2014-08-29T20:00:00.000Z">3 minutes left</time>
where datetime is the ISO date format for when the correct moment occured in the future
then inside of the element you would present the text how every you want to display it
By doing so you eliminate the slow bandwidth/DOM parsing & javascript compilation to when its start to count down.
When it has begun you should calculate how many hours/minutes/second there is left until that point in the feuter in every digest.
Then you are safe from the incorrect setTimeout/setInterval that doesn't always wait the exact same time, especially when the tab is idle (in the background)
where setTimeout(fn, 1000) could take 4 seconds if it where in the background.
Here is a example.
How you get the date and display it in the DOM is up to you
var finishDate = new Date(Date.now()+10000); // get point in future somehow
var tick = function() {
var now = new Date()
var difference = finishDate - now;
var hours = Math.floor(difference / 36e5),
minutes = Math.floor(difference % 36e5 / 60000),
seconds = Math.floor(difference % 60000 / 1000);
console.log(hours, minutes, seconds);
setTimeout(tick, now.getUTCMilliseconds())
}
tick() // Start the digest

How to automatically reload a web page at a certain time?

I have a website that I want to be reloaded at a certain time, like 3:35pm, not after a specific interval like 5min. How do I do that?
The following JavaScript snippet will allow you to refresh at a given time:
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
Then you can add a script tag to call the refreshAt() function.
refreshAt(15,35,0); //Will refresh the page at 3:35pm
Note that this code will refresh based on the client local time. If you want it to be at a specific time regardless of the client's timezone, you can replace get*() and set*() (except getTime()) on the time objects with their getUTC*() and setUTC*() equivalent in order to pin it to UTC.
<META HTTP-EQUIV="Refresh" CONTENT="5">
this will force page to reload every 5 seconds. Just calculate the correct interval and add it to content tag
I found this page with a similar question and used it to hack out a more specific answer that may be of use to some. For this project, we wanted to make sure that the page refreshed once a live event of global interest was about to go on, activating the player embed on the user's page (narrow use case, I know -- others might have a better use for it).
One challenge in the above answers was how to deal with time zone conversions, which was more of an issue for us because we wanted to make sure that the page refreshed at a specific day and time. To do this, I grabbed a UTC version of the target date and today's date, converted them to GMT, then set Andrew's timeout function to the difference between the two.
var target = new Date("January 28, 2011 13:25:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;
var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;
refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
Basically, when the page is accessed, calculate how much time is remaining between the access time and the time you want to reload the page, and use that remaining time in the meta refresh header. Obviously this would need to be done in a CGI script or web application, or possibly with SSI (server-side includes); it won't work if all you have is a static HTML file.
Another alternative would be to use Javascript, but it won't work if the client has Javascript disabled.
This worked better for my purposes.
If you're able to use Jquery and MomentJs, you can do this:
(function () {
var $ = require('jquery');
var moment = require('moment');
function refreshPageAtTime(expiration, countdownElement) {
var now = moment.utc();
console.log('now', now);
var expirationMoment = moment.utc(expiration, 'YYYY-MM-DD kk:mm:ss');
console.log('target', expirationMoment);
var secondsUntilRefresh = expirationMoment.diff(now, 'seconds');//http://momentjs.com/docs/#/displaying/difference/
console.log('diff in seconds', secondsUntilRefresh);
if (secondsUntilRefresh > 1) {
setInterval(function () {
secondsUntilRefresh--;
console.log('seconds remaining', secondsUntilRefresh, 'seconds');
if (secondsUntilRefresh <= 10) {
countdownElement.html(secondsUntilRefresh + '...');
if (secondsUntilRefresh === 0) {
console.warn('Refreshing now at ' + moment.utc());
window.location.reload(true);
}
}
}, 1000 * 1);
}
}
$(document).ready(function () {
var expiration = $('form').attr('data-expiration');
console.log('expiration', expiration);
$('.btn-primary:submit').after('<div id="countdownToRefresh" style="display: inline-block; color: #999; padding: 10px;"></div>');
refreshPageAtTime(expiration, $('#countdownToRefresh'));
});
})();
Basically, there are many javascript codes out there that can refresh the page ever so minutes or something, you can edit them to refresh at hours too. Like this one:
//enter refresh time in "minutes:seconds" Minutes: 0 to Whatever
//Seconds should range from 0 to 59
var limit = "0:30";
if (document.images) {
var parselimit = limit.split(":");
parselimit = parselimit[0] * 60 + parselimit[1] * 1;
}
var beginrefresh = function () {
if (!document.images) return if (parselimit == 1) window.location.reload()
else {
parselimit -= 1;
curmin = Math.floor(parselimit / 60);
cursec = parselimit % 60;
if (curmin != 0) curtime = curmin + " minutes and " + cursec + " seconds left until page refresh!";
else curtime = cursec + " seconds left until page refresh!";
window.status = curtime;
setTimeout("beginrefresh()", 1000);
}
}
window.onload = beginrefresh;
(now just calculate the minutes and seconds you want it to refresh, like for example noon everyday if it were noon now:
var limit = "1440:00";
Now you could use this code except, most of them don't work with server time, And with the information you provided us, we really can't do anything more. Edit your question and tell us if you want it to be timed with the servers time, or something else.
I hope this help,you can set the exact time for refresh
var target = new Date("November 18, 2019 10:00:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;
var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;
refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
if you using Flask you can set variable synchronized to network time. In the flash app
from datetime import *`
def syncRefresh():`
while (datetime.now().second % 10 !=0):`
continue`
return True`
and #app.route('/', methods =["GET"})
def table():
....
if syncRefresh():
refreshNow = True # refreshNow is the variable passed to the web page
and in the html page
{% if refreshNow %}
<meta http-equiv="refresh" content="1">
{% endif %}
refresh at a given minute and second → i.e. every hour at fixed time can be as follows:
<script type="text/javascript">
function refreshAt(minute, second) {
var date= new Date();
var hr = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
if(m == minute && s == second)
{
window.location.reload(true);
}
setTimeout(function() { refreshAt(minute, second); },600);
};
</script>
Use this to refresh the page every 20 seconds.
<META HTTP-EQUIV="refresh" CONTENT="20">

Categories