开发者

Refresh Div with Jquery at fixed time

开发者 https://www.devze.com 2022-12-24 22:49 出处:网络
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

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 开发者_如何学Go= $('#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...


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


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消