Pregunta

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");
¿Fue útil?

Solución

The problem is that you are only polling the server time once. You call showRemaining again and again, but the now time will never change, therefor the output will never change.

If you need to use server time, you need to send the request you are sending in postRequest everytime showRemaining is called and use it for now:

Some of this post was deleted since it was wrong

You can find an example in this jsfiddle, where I replaced the contents of postRequest with a stub to use the client time instead of making an Ajax call (since I don't have access to your time.php).

Of course, repeated server requests like that are quite inefficient, so you really should consider using the client's clock. You could also consider using the server time once and then use the Javascript clock to add to that time.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top