Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setTimeout works for endless recursive calls?

This is my recursive function :

function importTEI(index,data,header){
    if (index == data.length){return}

    var tei = new dhis2API.trackedEntityInstance();
    tei.excelImportPopulator(header,data[index]);
    tei.POST(requestCallback,requestCallback,index);

    function requestCallback(response){
        notificationCallback(response);
        setTimeout(function(){
            importTEI(response.importStat.index+1,importData,header);
        },0);
    }
}

The function importTEI is called within the function using setTimeout. When called without the setTimeout then after a few requests this error comes -

Uncaught RangeError: Maximum call stack size exceeded

But with setTimeout it runs forever....How come? What special thing is happening inside setTimeout? Is it no longer a recursive call?

Any tips are appreciated. Thnx.

like image 751
harsh atal Avatar asked Mar 05 '26 02:03

harsh atal


1 Answers

It's no longer a recursive call. The setTimeout is a callback in the future and that call would be at the "top of the stack". The existing call to your function sets up this callback and then finishes its execution, resulting in zero recursion.

like image 125
Jeff Watkins Avatar answered Mar 07 '26 16:03

Jeff Watkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!