1

I am trying to create a count-down timer using mysql, php and javascript. I am trying to make the ending-time a constant and stored in mysql server, then it is queried every second from javascript via php. Then, I am getting the current time in javascript, every second using new Date() function. subtracting the current time from ending-time gives me the time left.

However, my problem is that when the website is viewed in different devices, the current time queried using javascript is varied by seconds and sometimes even minutes... Please help me solve this problem.

Here's what I have tried.

setInterval(function() 
    {
    
    
    $.post('QueryTime.php', 'get=true', function(data,status) 
    {
        if(status)
            var endingtime = data;
        else
            alert("Server Error! Please refresh the page.");
    });
    
    endingtime = parseInt(endingtime);


    
    var now = new Date();
    now = now.getTime(); 
    var timeleft = (date - now)/1000;
},1000);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Light
  • 13
  • 3
  • possible duplicate of [Sync JS time between multiple devices](http://stackoverflow.com/q/10585910/1048572)? – Bergi May 20 '15 at 20:24
  • Just take the local time of you starting the request, the server time as the server says he did receive the request, and the local time of your receiving the response, and calculate your own offset based on that. – Bergi May 20 '15 at 20:27

1 Answers1

0

Do you mean the actual local time of the devices varies a bit? This is usually the case, more devices mean more times :) What you may want is to not get the time necessarily via new Date().getTime() every time but maybe to get the current time from the same remote location for every device.

This remote location can be your server, which holds the ending time as i understand or something from the internet:

Here's some code to get the Unix timestamp via an HTTP request in Javascript:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://currentmillis.com/api/millis-since-unix-epoch.php", false);
xmlHttp.send(null);
document.getElementById('info').innerHTML = xmlHttp.responseText;
<div id='info'></div>
Sandman
  • 2,577
  • 2
  • 21
  • 32