-1
 $.ajax({
    url: "data.php"
}).done(function(data) { 
    //code
});

how to wrap this in jQuery timeout function for example send an ajax request every 2 sec.?

M1X
  • 4,971
  • 10
  • 61
  • 123

3 Answers3

4

If you wrap this in a setInterval, you run the risk of sending your server a ton of requests with the potential of not getting them all back in order. Put a timeout inside the callback:

function runAjax() {
    $.ajax({
        url: "data.php"
    }).done(function(data) { 
        //code
        setTimeout(runAjax, 2000); //Run it again in 2 sec
    });
}

runAjax(); //I suppose we should start the AJAX :D
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

I would do something like this:

var ajax = null;
function callAjax()
{
  if(ajax != null)
     ajax.abort();
  ajax = $.ajax({
    url: "data.php"
  }).done(function(data) { 
    //code
  });
  setTimeout(callAjax, 1000); // Every 1 second
}
callAjax();

This code will execute the Ajax call once every 1 second. If another request is running, it will kill it before running another one.

A better way would be to use long polling: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery

Scalpweb
  • 1,971
  • 1
  • 12
  • 14
  • id rather but the timeout call in the done callback – Alex Sep 30 '13 at 13:13
  • Depends on what you want to do. If you want to ensure the requests are sent every second or if you want to launch it again one second after it succeeds. It's actually much different. – Scalpweb Sep 30 '13 at 13:14
  • Why not `if(ajax && ajax.readyState < 4)` – Johan Sep 30 '13 at 13:17
0

you can use setInterval.

var xhr;
setInterval(
   function runAjax() {
        if(xhr) {
            xhr.abort();
        }
        xhr = $.ajax({
            url: "data.php"
        }).done(function(data) { 

        });
    }, 2000
)

try like this.

Anil kumar
  • 4,107
  • 1
  • 21
  • 36