0

My following script works: but with one problem: it doesnt count down. It gives the right output (time now untill date) but doesnt update automatically.

Anyone nows whats wrong?

The main thing is this countdown timer works with server time (thats why the post, and time.php).

        <script>
var end = new Date('10/7/2013 7:0 PM');

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;

var now;
function startShowRemaining(strnow) {
now = new Date(strnow);
showRemaining();
}
function showRemaining() {
//var now = new Date(strnow);
    var distance = end - now;
    if (distance < 0) {

        clearInterval(timer);
        document.getElementById('countdown').innerHTML = 'EXPIRED!';

        return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById('countdown').innerHTML = days + 'days ';
    document.getElementById('countdown').innerHTML += hours + 'hrs ';
    document.getElementById('countdown').innerHTML += minutes + 'mins ';
    document.getElementById('countdown').innerHTML += seconds + 'secs';
}

timer = setInterval(showRemaining, 1000);

function postRequest(strURL) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    var xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 
   'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
        startShowRemaining(xmlHttp.responseText);
    }
}
xmlHttp.send(strURL); }
postRequest('time.php');      
</script>
<div id="countdown"></div>

TIME.PHP:

print date("m/d/Y, G:i:s");
4

1 回答 1

1

问题是您只轮询服务器时间一次。你showRemaining一次又一次地调用,但now时间永远不会改变,因此输出永远不会改变。

postRequest如果您需要使用服务器时间,则需要在每次调用时发送您发送的请求showRemaining并将其用于now

部分帖子因发错而被删除

您可以在这个 jsfiddle中找到一个示例,其中我将 的内容替换postRequest为存根以使用客户端时间而不是进行 Ajax 调用(因为我无权访问您的time.php.

当然,像这样重复的服务器请求效率很低,所以你真的应该考虑使用客户端的时钟。您也可以考虑使用一次服务器时间,然后使用 Javascript 时钟添加到该时间。

于 2013-10-07T17:22:54.523 回答