Naiya55
Naiya55

Reputation: 134

javascript how to run a function again after it ends

I have a function that updates a table on my html page through ajax. This ajax call takes an extremely long time to finish. I was lead to believe that the following code would run it again once the ajax call had finished with no memory leak, as the function would end before delay in setTimeout did. However, when I look at the processes with chrome's developer tool, I can see many instances of my function makeTable() going and I get the error Failed to load resource: the server responded with a status of 500 (Internal Server Error) in the console. Is there a better way to do this?

 function makeTable() {
    $.ajax({
        url: "TableView.asp",
        type: "GET"
    }).done(function (ret) {
        $("#info_display").html(ret);
    });
    setTimeout(makeTable, 5000);
 } 

Upvotes: 1

Views: 3725

Answers (4)

bipen
bipen

Reputation: 36531

Simply move makeYellowTable() function call inside a ajax callback

 function makeTable() {
    $.ajax({
        url: "TableView.asp",
        type: "GET"
    }).done(function (ret) {
        $("#info_display").html(ret);
        makeYellowTable(); //<--- here this function is called only after the ajax completes.
    });

} 

makeYellowTable() will only be called after ajax call completes. And it will be called once.

Upvotes: 1

instantaphex
instantaphex

Reputation: 1001

You have a couple of problems here. First, the purpose of the .done() method chained on the end of the $.ajax() call is to call some code when the response comes back from the server. Whatever logic you need to do need to be done in there, not by using setTimeout. Second, your php script is not working correctly. Without seeing that code I don't know what's going on but it looks like there is an error there which is causing your server to return 500.

Upvotes: 1

eisbehr
eisbehr

Reputation: 12452

Use success for preventing errors and call makeYellowTable there when it's finished.

function makeTable() {
    $.ajax({
        url: "TableView.asp",
        type: "GET",
        success: function() {
            $("#info_display").html(ret);
            makeYellowTable();

            // or with a timeout again
            // setTimeout(makeYellowTable, 5000);
        }
    });
}

Upvotes: 1

The

setTimeout(makeYellowTable, 5000);

Should be within callback function "done"

.done(function (ret) {
    $("#info_display").html(ret);
    setTimeout(makeYellowTable, 5000);
});

Upvotes: 1

Related Questions