views:

426

answers:

2

I've got a php script that tells me when the next bus is due, and at the moment I'm refreshing this into a div, using jquery, every minute or so. Now, because I know the time at which the data will change (after the bus has come), I want it to refresh the div at this time (or just after, doesn't really matter).

I should point out that I'm fairly new to js, but this is what I've got so far:

    var nextbustime = $('#bus').contents();
var nextbustime = new Date(nextbustime);
var now = new Date();

var t = nextbustime.getTime() - now.getTime();


var refreshId = setTimeout(function()
{
    $('#bus').fadeOut("slow").load('modules/bus.php?randval='+ Math.random()).fadeIn("slow");
}, t);

The div is loaded originally with a php include. Naturally, what I've done doesn't work at all.

Do I need some loops going on? Do I need to refresh the time calculator?

Please please help!

Thanks in advance...

A: 

Since you are using jQuery anyways, check out this jQuery plugin here: jQuery timer plugin

mana
A: 

I assume from your statements that the code works for the first refresh? What you need to do is handle the next several. Since the time may vary (it appears), setInterval probably won't work for you. What should work is calling your function again at the end of each timeout.

$(document).ready(function() {
    changeToNextBus();
});

function changeToNextBus() {
    var nextbustime = $('#bus').contents();
    var nextbustime = new Date(nextbustime);
    var now = new Date();

    var t = nextbustime.getTime() - now.getTime();

    var refreshId = setTimeout(function()
    {
        $('#bus').fadeOut("slow").
                  load('modules/bus.php?randval='+ Math.random()).
                  fadeIn("slow");
        changeToNextBus();
    }, t);
}
justkt
No, it doesn't work on the first refresh, which is part of the problem...And I just tried what you suggested (and variations of), and it causes a big ol' loop...Thanks anyway!
Ben C
@Ben C, is the value of t correct for the number of seconds at which you want the refresh? I'm unsure how you are going to do this without a loop - isn't that the point? You just need the loop to happen only at a set interval.Also, is the JavaScript that's getting loaded in the bus.php? Or is it elsewhere? My code assumed elsewhere.
justkt