4

How to send Ajax request on every 1s using JQuery ?

tcooc
  • 20,629
  • 3
  • 39
  • 57
Damir
  • 54,277
  • 94
  • 246
  • 365
  • 5
    It is quite possible that you can't. It is very common for a request to take more then 1 second to complete. So if you tried to do this you would almost certainly end up with a long queue of requests waiting for an available connection and for them to come back in different order to being sent out (creating a race condition). You probably want to send one request as part of the callback to the previous request coming back. – Quentin Mar 15 '11 at 10:10

5 Answers5

17

You probably don't want to send a request every second as David already noted.

Therefore, using setInterval is a bad idea.

Instead consider doing something like this:

function doAjax() {

  $.ajax({
   ...
   complete: function() {
    setTimeout(doAjax,1000); //now that the request is complete, do it again in 1 second
   }
   ...
  });
}

doAjax(); // initial call will start rigth away, every subsequent call will happen 1 second after we get a response
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
6

you can use setInterval, but setInterval ist not part of jQuery:

setInterval(function() {
    $.get(...);
}, 1000);
felixsigl
  • 2,900
  • 1
  • 23
  • 16
1

The interval 1 sec is small enough and it can be that you will start the second request before you receive response to the first request. So you should either start the next request after receiving of the previous one (see the suggestion of Martin Jespersen) or save jqXHR from the previous $.ajax request in a variable and use it to abort the previous request (see here an example)

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
0

if you use setInterval method, you may crush the browser, because setInterval is not waiting for ajax function to complete, if server is running slow or user's connection speed is low this may be cause running multiple ajax requests at the same tme

JNZ
  • 402
  • 5
  • 11
0
setInterval(myAjaxCall, 1000);

Obviously in the function myAjaxCall() you will do all you ajax stuffs with jquery.

Mauro Rocco
  • 4,980
  • 1
  • 26
  • 40