0

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?

2 Answers 2

2

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*/
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.