user3436467
user3436467

Reputation: 1775

jquery ajax on page load and subsequent ajax call after 5 mins crashes browser after a while

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:

  1. Call ajax on-page load
  2. Call ajax every 5 mins afterwards

Upvotes: 0

Views: 1030

Answers (1)

Bhushan Kawadkar
Bhushan Kawadkar

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

Related Questions