ndmweb
ndmweb

Reputation: 3480

best method for ajax loops

Im building a web app with some real-time features, chat, auto updating lists. What's the best way to do these interval updates via AJAX?

Right now I have something basic like:

updateAll();

function updateAll(){
 $.ajax({
  url: 'update-chat-list.php',
  success: function(data){
     setTimeout(function(){ updateAll(); },30000);
  }
 });
}

This seems like it does the job, but is this the most efficient way to keep hitting the server for requests to update the page?

Upvotes: 0

Views: 477

Answers (1)

Ry-
Ry-

Reputation: 224913

The most efficient way is to degrade gracefully:

1) Attempt to use the Web Sockets API for adding push functionality and real-time updates without a loop. This is the best solution for modern browsers right now.

2) Use an Ajax loop. You can improve your current code slightly by using setInterval instead of repeatedly calling setTimeout.

3) Fall back to timed page refreshes, <iframe>s or manual refreshes.

So, you can keep what you've got, but learn about the Web Sockets API.

Upvotes: 2

Related Questions