How to send Ajax request on every 1s using JQuery ?
-
5It 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 Answers
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

- 25,743
- 8
- 56
- 68
you can use setInterval, but setInterval ist not part of jQuery:
setInterval(function() {
$.get(...);
}, 1000);

- 2,900
- 1
- 23
- 16
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)
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

- 402
- 5
- 11
setInterval(myAjaxCall, 1000);
Obviously in the function myAjaxCall() you will do all you ajax stuffs with jquery.

- 4,980
- 1
- 26
- 40