tags:

views:

92

answers:

4

Hi,

I have a page which currently refreshes itself every 10 seconds. The page runs a series of database queries and shows the results.

The problem is that sometimes the queries take up to a minute to run but the page still refreshes every 10 seconds so I end up with 6 sets of database queries being run, and so on. I know this as I log the action in the database with start and end times of the queries.

$(document).ready(function() {
var refreshId = setInterval(function() {
       $("#content").load('myurl.php?id=1');                        
    }, 10000);                         
});

How can I change it so the refresh only happens when the page has finished processing queries or 10 seconds whichever is longest?

A: 

You can queue your ajax requests using a plugin like AjaxQueue.

Vikash
+2  A: 

Why not just set a flag and skip the reload if the last one hasn't finished yet? Something like the following (untested but shows the basic idea)

var loading = false;

var refreshId = setInterval(function() {
       if (loading) 
           return;

       loading = true;
       $("#content").load('myurl.php?id=1', function() {
           loading = false;
       });                        
    }, 10000);                         
});
fearofawhackplanet
This works great. Thanks!
Matt
+1  A: 

You can use setTimeout instead and reload the timer upon completion

sewa
+1  A: 

Instead of refreshing the page periodically, fetch the data via an AJAX call and when it's complete re-schedule the refresh again.

In pseudo code:

// Set initial timeout, 10 seconds
var refTimeout = setTimeout(refreshData, 10000);

function refreshData ()
{
    // Remove timeout, we won't be called again until AJAX call is complete
    clearTimeout (refTimeout);

     $.ajax ({url: 'mydatasource.php', data : { ... },
         success : function (data) {
         // Render data into content area...

         // Set timeout so we'll be called again in 10 seconds
         refTimeout = setTimeout (refreshData, 10000);          
         }
    });

}
axel_c