Jim Ord
Jim Ord

Reputation: 1

Using server-side clock in javascript

I am using some JavaScript to inspect a countdown hour minute target and then kick-off a php page:

window.setInterval(function() { // Set interval for checking
    var date = new Date();
    if (date.getHours() === 13 && date.getMinutes() === 31) { // Check the time
        location.href = "real_live.php?lotnum=1";
    }
}, 1000); // Repeat every 1000 milliseconds (1 second)

It's currently using the client side clock and functions perfectly. However, I need to use the server side clock and try as I may I have not found a working way to do this. Can you advise?

Upvotes: 0

Views: 1806

Answers (3)

Jim Ord
Jim Ord

Reputation: 1

With a little more research I have found a solution, which I believe is accurate. The question was asked in order to find the server-side time, which not all the answers did. But I believe that this Ajax abridged code does the trick.

	window.setInterval(function(){ // Set interval for checking
		var xmlHttp;
		function srvTime(){
		try {
			//FF, Opera, Safari, Chrome
			xmlHttp = new XMLHttpRequest();
		}
		catch (err1) {
			//IE
			try {
				xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
			}
			catch (err2) {
				try {
					xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
				}
				catch (eerr3) {
					//AJAX not supported, use CPU time.
					alert("AJAX not supported");
				}
			}
		}
		xmlHttp.open('HEAD',window.location.href.toString(),false);
		xmlHttp.setRequestHeader("Content-Type", "text/html");
		xmlHttp.send('');
		return xmlHttp.getResponseHeader("Date");
		}

		var st = srvTime();
		var date = new Date(st);
		if(date.getHours() === 14 && date.getMinutes() === 40){ // Check the time
			location.href = "real_live.php?lotnum=1";
		}
	},1000); // Repeat every 1000 milliseconds (1 second)

But thank you all very much for your input, which led me to this solution.

Upvotes: 0

Bwaxxlo
Bwaxxlo

Reputation: 1880

You should have two separate backend scripts for this. One for the timer which the client will trigger, and should it hit the time you want, you trigger your time-sensitive script.

So,

xhr.open("GET", "/time.php", false);
xhr.onload = function (e){
  //do your magic with the results to real_live.php
}

Upvotes: 1

S.Krishna
S.Krishna

Reputation: 876

Use Date.UTC. This ensures that its the same, no matter where the client machine is located. You can read more on the syntax here

Upvotes: 0

Related Questions