i'm trying to build a page that takes the current hour and minute from the javascript date module and then makes the background color unique based off of that info.
what needs to change to get the html liked with the javascript? (new to this if you cant tell).
HTML
<html>
<head>
<meta charset="UTF-8">
<title>New color for each minute of day</title>
</head>
<body id="body">
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT
var body = document.getElementById("body");
var a = 0;
var b = 0;
var c = 0;
function currentTime() {
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
minute = formatTime(minute);
text.innerHTML = hour + ":" + minute;
return minute
}
function changeColor() {
for (minute =< 59; a + 1);
for (hour =< 24; b + 10);
}
function setScene() {
timeValue = currentTime();
}
window.addEventListener("load", initialScene, false);
document.body.style.backgroundColor= 'rgb(' + a + ',' + b + ',' + c + ')';
Omit the CSS (style tag) in the first example and just use plain JS.
document.getElementsByTagName("body")[0].style.background="rgb("+a+", "+b+", "+c+");";
should do it
That's the main problem. Also, in your changeColor function, you are not using the for loop correctly, although you've got the right idea.
for (minute=0;minute<=59;minute+=1) {
a=minute;
}
for (hour=0;hour=<24;hour+=10) {
b=hour;
}
for loops can be a confusing subject for newcomers to JS, but there are some great tutorials online. Do a Google Search and really take the time to learn what a for loop does sometime, it's a good thing to know.
PS I don't see where c is defined.
I think you ask for a changing background for every minute of the day. You need to define a recurring function that reads the time and changes the color. You have that as setScene.
Now you can call it every 60 seconds automatically by pasting the following somewhere inside initialScene:
setInterval(setScene, 60000);
Related
I'm trying to make a background that changes the color on the time of day. However I can't seem to fix my parameters. Put them in variables. Input from HTML to JavaScript is fixed.
Feels like I'm missing something very obvious. (new to JavaScript and coding in general).
jQuery(document).ready(function($) {
function alerts(alert1, alert2, alert3, alert4, alert5, alert6) {
var hours = new Data().getHours();
if (alert1.empty() || alert2.empty() || alert3.empty() || alert4.empty() || alert5.empty() || alert6.empty()) {
alert1 = 0;
alert2 = 12;
alert3 = 12;
alert4 = 17;
alert5 = 17;
alert6 = 24;
if (hours >= alert1 && hours < alert2) {
document.body.style.backgroundColor = "#fceea1";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "#dbbc0a";
} else if (hours >= alert5 && hours < alert6) {
document.body.style.backgroundColor = "#706527";
} else {
}
}
};
body {
font-family: sans-serif;
background: white;
font-size: 150px;
color: #333;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welkom</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js">
alerts(0, 12, 12, 17, 17, 20);
</script>
</body>
</html>
The working code, explanations are after the code:
index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Welkom</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <!-- Includes Jquery -->
<script src="js/index.js"></script> <!-- Includes the script for background change -->
</body>
</html>
js/index.js
jQuery(document).ready(function( $ ){
function alerts (alert1, alert2, alert3, alert4) {
var hours = new Date().getHours(); //The proper inclusion of date
if (alert1 == undefined) { //Undefined is JS keyword which set
alert1=0; //when variable was declared, but undefined, no defenition
}
if (alert2 == undefined) {
alert2=12;
}
if (alert3 == undefined) {
alert3=17;
}
if (alert4 == undefined) {
alert4=24;
}
//The redundant variables were removed and you can reuse variable
// for multiple if statements
if (hours >= alert1 && hours < alert2) {
document.body.style.backgroundColor = "#fceea1";
} else if (hours >= alert2 && hours < alert3) {
document.body.style.backgroundColor = "#dbbc0a";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "#706527";
} else { //Just a quick comment, you are able not to even print
// else statement, you can just leave it out
}
}
alerts(); // Calls the function
}); // the ) bracket closes Jquery
css/style.css
body {
font-family: sans-serif;
background: white;
font-size: 150px;
color: #333;
} /*Unchanged*/
Explanations
There was 5 main problems with your code.
First:
The 'if' statement
Your 'if' statement for checking if the values were empty ALSO included the code for execution the function itself.
So if you called your code with variables set, the code won't execute.
Second:
The wrong import of jQuery
What you actually meant was var hours = new Date().getHours(); instead of var hours = new Data().getHours();.
Its very simple error, easy fix.
Third:
alert1.empty()
This is not correct approach. Much cleaner is to to check like alert1 == undefined.The undefined keyword is for variable which were declared, but they haven't been defined. Plus not all JavaScript interpreters (browsers) support .empty().
Fourth:
The or in the 'if' statement
The operator || is evil. In code example you provided if any of those variables missed it will override ALL variables to default values you specified. Because of that I have divided them in separate 'if' statements.
Fifth:
Redundant variables
The variables alert2 and alert3 are redundant, like variables alert4 and alert5. By redundant I mean they have the same value, while you can just use one variable, but in multiple 'if' statements. Remember: You can use the same variable in multiple 'if' statements. I removed two variables and modified version of the code execution is:
if (hours >= alert1 && hours < alert2) {
document.body.style.backgroundColor = "#fceea1";
} else if (hours >= alert2 && hours < alert3) {
document.body.style.backgroundColor = "#dbbc0a";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "#706527";
} else {
}
I think experimenting with random little projects is a great way to learn, so I made a simple script that does what you described with comments so you can try to understand how everything works!
The color looks pretty odd and ugly, but that's just because of the values I gave it, so feel free to mess around with weights and different measurements of time!
function changeColor() {
var d = new Date(); // Creates a 'date' object
var ms = d.getMilliseconds(); // Gets the current millisecond
var minute = d.getMinutes(); // Gets the current minute
var second = d.getSeconds(); // Gets the current second
/*
Other methods of obtaining the time:
d.getFullYear() Get the year as a four digit number (yyyy)
d.getMonth() Get the month as a number (0-11)
d.getDate() Get the day as a number (1-31)
d.getHours() Get the hour (0-23)
d.getTime() Get the time (milliseconds since January 1, 1970)
d.getDay() Get the weekday as a number (0-6)
*/
document.body.style.backgroundColor = 'rgb(' + ms/4 + ',' + minute + ',' + second + ')';
// This sets the backgroundColor of the document to an RGB value where red is the milliseconds, green is the minute, and blue is the second
// Note: I divided the millisecond value by 4 because the highest possible value is 255 and the millisecond value can reach 999.
// It would still work without dividing it, but the color wouldn't change as much because it would interpret 255-999 as 255
}
var interval = setInterval(changeColor, 100) // Runs the changeColor() function every .1 seconds
// Note: This would still work if I didn't set it as a variable, but it's good practice to set intervals as variables so you can use clearInterval(variable)
This is my countdown javascript code everyday on 23:00 of local time will finish and after 1 hour again will start to countdown for tomorrow and this continues. I wanted to know is it possible to add PHP code to this till after countdown finished everyday It adds "5" to my "Credit" column ("Credit" + 5 ) in my MySQL automatically ? appreciate for any kind of guidance.
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'Your match started!';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(23,0,0,0);
var myEnd = new Date()
myEnd.setHours(24,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<font face="Trebuchet MS">
<div id="foo" style="color: white; font-size: 14px; font-weight: bold;"></div>
Jquery Ajax is the way to go here i guess.
It seems like you are very new and might not know what ajax is.
In short with Ajax you can call a webpage url in the background. So You could call www.yourdomain.com/addCredits.php
It will do the same as if you would visit that url in your browser. Just write your SQL Code inside that addCredits.php File and you're done.
Just add something like this to your javascript:
$.ajax({url: "addCredits.php"});
You will have to embed jquery inside your document first though.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
And also you might want to wait for that script to load before you call that function:
$( document ).ready(function() {
$.ajax({url: "addCredits.php"});
});
Edit:
Your Counter acutally seems to continue in a loop since it keeps up calling itself in the end.
But i would say just put it where your setTimeout is at the end of your function.
Edit2:
Here is an Example with a Clock, your code seems to be over-complicated to be honest. It doesn't really work when i put it in a fiddle aswell...
You could just use this instead:
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
I created a countdown timer in Javascript; it was successful, expect not complete. In fact, mathematically, it is correct, but Google Chrome's browser settings "pause" (for lack of a better term) SetInterval/Timeout, which means that if a user of my countdown program switches between tabs on their browser, then the execution of the function will not occur exactly at the set time limit.
I need help implementing this basic time logic from W3Schools:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
and this attempt to account for the browser SetInterval/Timeout interference: http://jsfiddle.net/7f6DX/31/
var div = $('div');
var a = 0;
var delay = (1000 / 30);
var now, before = new Date();
setInterval(function() {
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if(elapsedTime > delay)
//Recover the motion lost while inactive.
a += Math.floor(elapsedTime/delay);
else
a++;
div.css("right", a);
before = new Date();
}, delay);
Thanks for any help that you can provide.
You should use real-world time to update your timer instead of relying on the accuracy of setInterval.
The w3schools example you gave does exactly this; every 500ms it grabs the current time, formats it, and updates the display. When the tab is inactive, this update may occur less frequently than 500ms (Chrome can slow it down to once every 1-2s), but nevertheless, when the update does occur, you will display correct information.
// countdown for 1 minute
countdown(60);
function countdown(seconds) {
// current timestamp.
var now = new Date().getTime();
// target timestamp; we will compute the remaining time
// relative to this date.
var target = new Date(now + seconds * 1000);
// update frequency; note, this is flexible, and when the tab is
// inactive, there are no guarantees that the countdown will update
// at this frequency.
var update = 500;
var int = setInterval(function () {
// current timestamp
var now = new Date();
// remaining time, in seconds
var remaining = (target - now) / 1000;
// if done, alert
if (remaining < 0) {
clearInterval(int);
return;
}
// format
var minutes = ~~(remaining / 60);
var seconds = ~~(remaining % 60);
// display
document.getElementById("countdown").innerHTML
= format(minutes) + ":" + format(seconds);
}, update);
}
function format(num) {
return num < 10 ? "0" + num : num;
}
<div id="countdown"></div>
Run this snippet and switch around to different tabs. Your countdown will be off by a maximum of 500ms (the update frequency).
For what it's worth, a similar idea can be applied to animations.
When designing an animation, you should have a formula for the position x as a function of time t. Your rendering clock (whether it is setInterval, setTimeout, or requestAnimationFrame) is not necessarily reliable, but your physics clock (real-world time) is. You should decouple the two.
Every time you need to render a frame, consult the physics clock for the time t, calculate the position x, and render that position. This is a really great blog post which goes into great detail on animations and physics, from which I borrowed the above idea.
The following code is a countdown timer. It pulls an ending datetime stamp from mySQL and uses it to count to. The issue is that the mysql time may be in a different time zone than the client who is looking at the page with the timer.
I also pull the current timestamp from mySQL with NOW(), thinking that this would allow the timer to count as the user who created it intended.
if I put the NOW() value in this snippet
var timeDiff = target - (new Date());
like so
var nt='2015-03-11 05:12:15'.split(/[- :]/);
var timeDiff = target - (new Date(nt[0],nt[1]-1,nt[2],nt[3],nt[4],nt[5]));
the counter shows the correct time left when the page loads but does not count interactively any longer. I think I need to get the difference in hours between the clients local time and the mySQL NOW() and adjust the date in this line to get the interactive timer to run.
var timeDiff = target - (new Date());
nothing I try seems to work.
This is the working script if the client happens to be int he same time zone.
<script language="javaScript">
document.write(hrs);
function timeDiff(target) {
function z(n) {return (n<10? '0' : '') + n;}
var timeDiff = target - (new Date());
var hours = timeDiff / 3.6e6 | 0;
var minutes = timeDiff % 3.6e6 / 6e4 | 0;
var seconds = timeDiff % 6e4 / 1e3 | 0;
if (hours<0 || minutes<0 || seconds<0) {
document.getElementById('divBody').style.display='none';
document.getElementById('divExpired').style.display='';
return '<b>EXPIRED</b>';
}
else {
return '<b>' + z(hours) + '</b> Hours, <b>' + z(minutes) + '</b> Mins, <b>' + z(seconds) + '</b> Secs';
}
}
function doCountDown(target) {
document.getElementById('timer').innerHTML = '<img src=\"/backhaul/images/my/al-active.png\" class=\"vm2\" /> <span style=\"color:#c40000\"><b>EXPIRES IN</b></span>: ' + timeDiff(target);
var lag = 1020 - (new Date() % 100);
setTimeout(function(){doCountDown(target);}, lag);
}
window.onload = function() {
//Insert Expiratin Date from mySQL into t var
var t='2015-03-12 00:00:00'.split(/[- :]/);
doCountDown(new Date(t[0],t[1]-1,t[2],t[3],t[4],t[5]));
}
</script>
There are many ways of doing this, but I'll elaborate on two ways.
Method 1 : Adjust the time on the client side
One way is what you are trying to do which is to get the current time of the server and find the difference with the client's current time. You can simply adjust the server target time to the client's time. This can be done with
var serverDifference=Date.parse(mysql_data.now)-Date.now()
var target=Date.parse(mysql_data.server_time_in_two_hours)-serverDifference
Then you can input it into your function without problem.
Method 2: Calculate the times remaining, server side
Since you just need a countdown timer, I think it's more appropriate to simply send the seconds left server side. This can be done with SQL using
select timestampdiff(SECOND,now(),end_time) seconds_left from timers;
Then you simply just make a timer that counts down based on the number of seconds left instead of a target date. You can calculate the number of seconds left by deducting the time that the javascript has run from the time received from the server. So something like
var client_start=Date.now()
function timeDiff_fromseconds(target) {
function z(n) {return (n<10? '0' : '') + n;}
var timeDiff =target-(Date.now()-client_start)
var hours = timeDiff / 3.6e6 | 0;
var minutes = timeDiff % 3.6e6 / 6e4 | 0;
var seconds = timeDiff % 6e4 / 1e3 | 0;
if (hours<0 || minutes<0 || seconds<0) {
return '<b>EXPIRED</b>';
}
else {
return '<b>' + z(hours) + '</b> Hours, <b>' + z(minutes) + '</b> Mins, <b>' + z(seconds) + '</b> Secs';
}
}
There is also performance.now() as suggested by #dandavis. This returns the number of milliseconds since the tab opened and is accurate to 1/1000th of a millisecond. And this doesn't change even if the system clock of the client browser changes. For full support, you should use a polyfill (As of the time of this writing, iOS Safari doesn't support it). In this context we can replace Date.now() with it.
JSFiddle Demo:
http://jsfiddle.net/3o3u5r5j/1/
If it is possible to get remaining amount of seconds from database instead of expiry time (meaning to calculate it at the server and send to the client). Then you can use following code (sample). Fiddle
var countDownId;
var timer;
function countDown(){
console.log(timer--);
if(timer<=0){
clearInterval(countDownId);
alert('time expired');
}
}
function startCountDown(secondsToExpire){
var milliseconds = 1 * 1000 ;// 1 second
timer = secondsToExpire;
countDownId = setInterval(function() { countDown();},milliseconds);
}
window.onload = function() {
//Insert remaining time from expiration
var timeRemaining = 5;
startCountDown(timeRemaining);
}
You can tweak this to suit your needs.
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">