Reputation: 1775
I am trying to execute an ajax call on page load then subsequently every 5 mins. This seems to work at first but overtime it seems ajax is called heaps of times at once which ends up crashing my browser. When I check the browser development console (network tab) i can see heaps of requests sent at once and increases each time.
$(document).ready(function(){
function sendRequest(){
$.ajax({
url: "data.php",
success: function(data){
//do stuff with data..
},
complete: function() {
setInterval(sendRequest, 300000); // Call AJAX every 5 mins (in milliseconds)
}
});
};
sendRequest();
});
Is there anything wrong with the above code snippet or way to improve it to ensure only one ajax is called after 5 mins.
Just to reiterate what I am trying to do:
Upvotes: 0
Views: 1030
Reputation: 28513
You can calling setInterval
on every ajax call complete which is in result setting interval call of sendRequest
method multiple time and causing issue.
call setInterval
just once outside the ajax call which will call sendRequest
method for every 5 min, see below code
$(document).ready(function(){
function sendRequest(){
$.ajax({
url: "data.php",
success: function(data){
//do stuff with data..
},
complete: function() {
}
});
};
sendRequest();
setInterval(sendRequest, 300000); // Call AJAX every 5 mins (in milliseconds)
});
Upvotes: 1