Currently, I am using an XMLHTTPRequest to get the time and date from an Apache server. The code below shows that...
$(document).ready(function() {
$("#loadtime").load("getdatetime.php");
setInterval(function() {
$("#loadtime").load('getdatetime.php?randval=' + Math.random());
}, 1000);
$.ajaxSetup({cache: false});
});
Obviously I do not want to send an http request every second. Below is some code that I am experimenting with.
function getTime() {
var hr = new XMLHttpRequest();
var url = "getdatetime.php";
var myRandom = parseInt(Math.random() * 999999999);
hr.open("GET", url + "?rand=" + myRandom, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState === 4 && hr.status === 200) {
var serverTimeStamp = hr.responseText;
var displayTime = Date(serverTimeStamp);
document.getElementById("clock").innerHTML = displayTime;
}
};
hr.send(null);
return false;
}
The function above grabs a PHP time stamp via PHP built-in time() function that returns the number of seconds since the UNIX epoch. The PHP time stamp can be conveniently placed inside JavaScript's Date() function. So now I am able to return the server's time via HTTP request. The goal is to send one HTTP request every 5mins, instead of every second. So every 5mins I need to grab the Apache time stamp and then iterate on that time stamp...
// Sudo code:
// serverTimeStamp += 1000 (milliseconds)
// iterate on serverTimeStamp for 5mins
// send new HTTP request to get current Apache time stamp
// restart iteration, etc...
I have already discovered that I have no clue how to iterate upon serverTimeStamp asynchronously. I need the clock to iterate in real time and then sync back up with the server every 5mins. How can this be done? I have done some research on Google but I cannot find a simple explanation, just custom functions and references to Node.js, which I am not using. Any help or suggestions would be much appreciated.