How to send Ajax request on every 1s using JQuery ?
setInterval(myAjaxCall, 1000);
Obviously in the function myAjaxCall() you will do all you ajax stuffs with jquery.
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
you can use setInterval, but setInterval ist not part of jQuery:
setInterval(function() {
$.get(...);
}, 1000);
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)
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