Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this recursion or not

function x(){
  window.setTimeout(function(){
     foo();
     if(notDone()){ 
        x();
     };
  },1000);
}

My concern being unbounded stack growth. I think this is not recursion since the x() call in the timer results in a brand new set of stack frames based on a new dispatch in the JS engine.

But reading the code as an old-fashioned non JS guy it makes me feel uneasy

One extra side question, what happens if I scheduled something (based on math rather than a literal) that resulted in no delay. Would that execute in place or would it be in immediately executed async, or is that implementation defined

like image 245
pm100 Avatar asked Nov 11 '14 23:11

pm100


People also ask

What is an example of recursion?

A classic example of recursion For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

How do you know if a function is recursive?

To find the nth term, for example, you need to know the previous term and the term before that one. This is how you can determine whether a particular function is recursive or not. If the function requires a previous term in the same sequence, then it is recursive.

When should I not use recursion?

Recursion is avoided generally because it makes the code less readable and harder to maintain and debug. If you have low resources as paxdiablo said stack space might be valuable for you so you should avoid using it then too.


2 Answers

It's not - I call it "pseudo-recursion".

The rationale is that it kind of looks like recursion, except that the function always correctly terminates immediately, hence unwinding the stack. It's then the JS event loop that triggers the next invocation.

like image 88
Alnitak Avatar answered Oct 09 '22 12:10

Alnitak


It is recusive in a sense that it is a function that calls itself but I believe you are right about the stack trace being gone. Under normal execution the stack will just show that it was invoked by setTimeout. The chrome debugger for example will allow you to keep stack traces on async execution, I am not sure how they are doing it but the engine can keep track of the stack somehow.

No matter how the literal is calculated the execution will still be async.

setTimeout(function(){console.log('timeout');}, 0);console.log('executing');

will output:

executing
undefined
timeout 
like image 22
pllee Avatar answered Oct 09 '22 12:10

pllee