A J A J - 4 months ago 11
Javascript Question

Avoid Calling a function repeateadly unless its job is finished

I have a function that needs to be called after 5 seconds time interval. This function processes AJAX request in the background (the request goes to other website, so it may take a few seconds). The function is as follows:

function myFunction() {
var sendData = {
cid: cid
};
$.post('xyz.com/somepage.php', sendData, function(response) {
//processes the response
});
setTimeout(myFunction, 5000); //call again after 5 seconds
}


I need to consider a fact that some users may have slow internet connection and the request can take time more than 5 seconds. So, I need to avoid calling that function (or we say avoid sending request) again until its job is finished. I tried the method given in the last paragraph on this link, but it didn't work. Any suggestion? Thanks.

Answer

You can call the function on completion of ajax call

function myFunction() {
    var sendData = {
        cid: cid
    };
    $.post('xyz.com/somepage.php', sendData, function(response) {
        //processes the response
    }).done(function() {
        setTimeout(myFunction, 5000); //call again after 5 seconds
    });
}
Comments