c830
c830

Reputation: 514

Will setTimeOut function in recursive function cause stack overflow?

Does the following function cause stack overthrow eventually?

var isFinish= false;  
function foo(){         
// ajax call       
//in ajax success   
success: function(response){
setTimeout(function(){ 
     if (!isFinish)
     {            
       foo();   
     }    
     },1000);    
    }   
 }   

Upvotes: 2

Views: 188

Answers (3)

jfriend00
jfriend00

Reputation: 707696

There is no problem with calling foo() again from setTimeout(). This is NOT actually recursion because the first invocation of foo() has actually finished executing before the second invocation starts on the setTimeout().

So, there is no buildup of the stack at all.

Upvotes: 3

user1106925
user1106925

Reputation:

It shouldn't. setTimeout is asynchronous (presumably as is your AJAX request), so foo is able to exit immediately.

If jQuery has memory leaks in its $.ajax, then that's another issue.

Upvotes: 4

bretterer
bretterer

Reputation: 5781

From my experience I have not had an issue with this type of function. I would feel comfortable using this code on my server and application.

Upvotes: 0

Related Questions