简体   繁体   中英

Time queried using Javascript varies with Different Devices?

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.. thanks in advance.

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);

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM