harsh atal
harsh atal

Reputation: 409

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.

Upvotes: 3

Views: 381

Answers (2)

Ganesan Srinivasan
Ganesan Srinivasan

Reputation: 337

setTimeout function works only once. Look into your code. Inside the startTime function , you are calling the same function again in 0 ms. if you want it to repeat for sometime, use setInterval instead. This function returns a id using which you can stop it whenever you want.

refer this answer: Why does the setTimeout function execute forever?

Upvotes: 0

Jeff Watkins
Jeff Watkins

Reputation: 6359

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.

Upvotes: 4

Related Questions