Javascript时钟?

Tea*_*zom 1 javascript php timer clock

我用PHP获得GMT时间,我想像时钟一样计算它.

<?php $time = gmdate('H:i:s'); ?>

<script>var time = <?php echo($time) ?>;
    setInterval(function() {
        time += 1;
        $("#timediv").text("Current time (GMT): " + time);
        //somehow convert it to 11:44:31 AM ??
    }, 1000);
</script>
Run Code Online (Sandbox Code Playgroud)

可以帮助我吗?

Rob*_*bok 5

首先,依靠setTimeout/setInterval精度来显示时间并不是一个好主意.有多种原因使它们不那么准确,比如CPU减速.这就是为什么你应该使用Date对象,它使用实际的时钟.

当我想在客户端使用我的服务器时间时,这就是我所做的事情:

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

<!-- dateFormat plugin for nice and easy time formatting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>

<script>
    var clientTime = (new Date()).getTime(),
        serverTime = <?php echo time() ?> * 1000,
        difference = clientTime - serverTime;

    setInterval(function () {
        var now = new Date();

        now.setTime(now.getTime() - difference);

        $("#timediv").text("Current time (GMT): " + $.format.date(now, "hh:mm:ss a"));
    }, 1000);
</script>
Run Code Online (Sandbox Code Playgroud)

它背后的关键概念是计算服务器时间和客户端时间之间的差异.然后,您将客户端(每次创建new Date())标准化为差异.我们仍在使用setInterval,但即使由于某种原因它被延迟或加速,显示的时间仍然是正确的.