yazanpro yazanpro - 5 months ago 10
Ajax Question

Will Recursively Calling Web Service in JavaScript Cause StackOverflow

I have a migration procedure that might take 2 to 3 days to finish. I'm afraid that the following implementation might raise a StackOverFlow exception due to the recursive aspect of it. Does JavaScript actually build a huge stack in order to execute this code? If so, what would be a better implementation? I might call this service about 10 millions times.

function mainFunc() {
var url = getMyUrl();
$.ajax({
url: url,
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (remaining) {
if(remaining > 0) {
mainFunc();
}
else {
alert('done');
}
},
error: function (x, e) {
alert('error!');
}
});
}

Answer

First of all, this definitely doesn't sound like something that should be done from the browser, but handled server side instead.

That being said, Your recursion is happening asynchronously so a stack overflow won't happen for sure.
Depending on your exact code ( more specifically, which values exactly are being included in the closures ), this might start piling up memory. You will also be using additionally memory because the success and error function's will be re-created every-time you call mainFunc.

You can solve this function memory allocation issue fairly easiliy by declaring those functions outside mainFunc and then pass a reference to them inside the mainFunc function.

Doing this won't absolve you completely from preventing a memory exception off course. This really depends on the actually code and what references you are keeping on each iteration.

In order to determine if your code is hanging on to resources during this long process, you will ether have to read the code and figure out where you're code is "leaking", or dive into memory profiling options:

https://developer.chrome.com/devtools/docs/javascript-memory-profiling

Example to factor out closures:

function mainFuncSuccess(remaining) {
    if(remaining > 0) {
       mainFunc();
    }
    else {
        alert('done');
    }
}


function mainFuncError() {
    alert('error!');
}

function mainFunc() {
        var url = getMyUrl();
        $.ajax({
            url: url,
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: mainFuncSuccess,
            error: mainFuncError
        });
    }
Comments