Running a real-time clock with AJAX

2019-08-31 23:08发布

问题:

Now that I was helped getting AJAX running just great, I'm having problems running a clock function with it....

Clock code (located in the head):

<script type="text/javascript">

var ampm = "AM"; //Default
var message="";


function startTime()
{
var today = new Date(); //Number goes here
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
//t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
message = "How long you gonna sit there?";
  }
return i;
}

function checkTime2(i)
{
if (i>12)
  {
  i=i-12;
ampm="PM";
  }
return i;
}


//setInterval(startTime,1000);

</script>

AJAX code (bottom of the document):

<script type='text/javascript'>
function CheckForChange(){
    //alert("<?echo (count($listArray)) . ' and ' . count(file($filename_noformat))?>");
    //if (<?echo count($listArray)?> == <?echo count(explode("\n", $filename_noformat))?>){
        //setInterval("alert('Yup, it is 1')", 5000);

        //alert('Now it is changed');
    //}

    var ajaxReady = new XMLHttpRequest();
    ajaxReady.onreadystatechange = function(){
        if (ajaxReady.readyState == 4){
            //Get the data
            //document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
            //startTime();
            //alert("here");
            //alert(ajaxReady.responseText);
        }
    }
    ajaxReady.open("GET","ServerTime.php",true);
    ajaxReady.send(null);
}

setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
</script>

What I'm trying to do is pass the input from ServerTime.php which is just a count of milliseconds from Unix epoch, into the clock, so the clock is being updated by the AJAX every second and the clock function runs with a new starting value each second.... I used to have parameters for the clock function before I realized the clock wasn't even getting called.

What do you think is wrong? I'm guessing it has something to do with the clock and the caller of the clock being in two different script tags, but I can't think of how to get around it. For some reason when I moved the AJAX part into the same script tag, following the clock, nothing happens.

To Kolink: I have this

function getTheNow(){
TIMESTAMP = <?php echo time(); ?>000;
    offset = new Date().getTime()-TIMESTAMP;
    setInterval(function() {
        var now = new Date();
        now.setTime(now.getTime()-offset);
        // print out the time according to the variable `now`
//alert(now);
    },5000);
return now;
}


function startTime()
{
var now = getTheNow;
//alert(now);
var today = new Date(); //Number goes here
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
message = "How long you gonna sit there?";
  }
return i;
}

function checkTime2(i)
{
if (i>12)
  {
  i=i-12;
ampm="PM";
  }
return i;
}


setInterval(startTime,1000);

回答1:

Computer clocks are not so inaccurate that you have to re-sync them every second. Try every ten minutes, or even every hour.

In fact, I just do away with synchronising altogether. It is far easier to do this:

<script type="text/javascript">
    TIMESTAMP = <?php echo time(); ?>000;
    offset = new Date().getTime()-TIMESTAMP;
    setInterval(function() {
        var now = new Date();
        now.setTime(now.getTime()-offset);
        // print out the time according to the variable `now`
    },1000);
</script>


回答2:

JavaScript 101 error

setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);

You are not assigning the function, you are calling/executing them and saying what ever is returned from these functions should be set. Drop the () so you are referencing the functions.

setInterval(CheckForChange, 1000);
setInterval(startTime,1000);