skyz
skyz

Reputation: 53

Ajax post to PHP script that queries MySQL DB every 5 seconds performance/problems?

I have a jQuery ajax function that posts to a PHP script which then retrieves some fields from the database and returns them to the client. The ajax function is run every 5 seconds after a button is clicked:

window.setInterval(function()
    {
        ajaxCall("lobby");
    }, 5000);

The ajax function:

function ajaxCall(param) 
    {
        $.ajax({
            url: "script/lobby.php",
            type: "post",
            dataType: "json",
            data: param,
            success: function(data, textStatus, jqXHR){
                //do stuff with data
            },
            error:function(jqXHR, textStatus, errorThrown){
                //show error
            }
        });
    }

Is this a good way of doing it? I have read somewhere that if done wrongly it may create a backlog of calls. How would I prevent that or is there a better way instead of querying a database every 5 seconds for each user?

Upvotes: 0

Views: 282

Answers (2)

psx
psx

Reputation: 4048

You could experiment with a sliding scale of timings. I'm sure there's a name for it, but initally start at 1 second per check, then after so many "null updates" ie. theres no change, extend out to 5 seconds between checks, then 15 seconds, etc.

When you get a data response that indicates activity, you could then reset the checks to 5 seconds.

Upvotes: 0

KJ Price
KJ Price

Reputation: 5974

Instead of creating an interval, don't start the next call to the server until the previous is completed:

function ajaxCall(param) 
{
    $.ajax({
        url: "script/lobby.php",
        type: "post",
        dataType: "json",
        data: param,
        success: function(data, textStatus, jqXHR){
            setTimeout(function () {/*Use setTimeout instead of setInterval*/
                 ajaxCall();/*This will keep getting called until an error is hit*/
            }, 5000); 
            //do stuff with data
        },
        error:function(jqXHR, textStatus, errorThrown){
            //show error
        }
    });
}

ajaxCall(); /*This starts things off*/

Upvotes: 2

Related Questions