mickeyb mickeyb - 4 months ago 20
Javascript Question

RefreshID = setinterval not working?

I'm building a weather data live website, using a template kindly donated to me. It's supposed to refresh the element data every 5 seconds or whatever I set but in every browser I'm having to refresh or force refresh or even delete all history, cookies, etc. to get the latest data. I don't really want to refresh the whole page.

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

function windspeed() {
$('#windspeed').load('windspeed.php');
}
var refreshId = setInterval(windspeed, 5000);

Answer

The problem: you're doing multiple url requests in the same time because you're using setInterval. Use setTimeout instead, but only when the url request finish.

You've to replace the .load method by $.ajax because it has the success callback:

var refreshId;

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

function windspeed() {
    $.ajax({
        cache: false,
        success: function(response) {
            $('#windspeed').html(response);
            setTimeout(windspeed, 5000);
        },
        type: 'GET',
        url: 'windspeed.php'
    });
}