Is it recursion or not

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

My problem is unlimited stack growth. I think this is not a recursion, since calling x () in the timer will create a new set of stack frames based on the new send in the JS engine.

But reading the code like an old-fashioned guy without JS, I feel awkward

One additional question is what happens if I plan something (based on math, not literal) that does not lead to a delay. Whether this will be done in place or will be executed immediately after aync or will the implementation be determined

+9
javascript recursion
Nov 11 '14 at 23:14
source share
4 answers

In a sense, it is disgusting that it is a function that calls itself, but I believe that you are correct in that the stack trace did not pass. On normal execution, the stack will simply show that it was called setTimeout. The Chrome debugger, for example, will allow you to save stack traces when running async, I'm not sure how they do it, but the engine can track it somehow.

Regardless of how the literal is computed, execution will still be asynchronous.

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

will output:

 executing undefined timeout 
+2
Nov 11 '14 at 23:27
source share

This is not - I call it "pseudo recursion."

The rationale is that it looks like recursion, except that the function always finishes correctly immediately, so it spins the stack. Then this is a JS event loop that fires the next call.

+3
Nov 11 '14 at 23:19
source share

One additional question is what happens if I plan something (based on math, not literal) that does not lead to a delay. Whether this will be done in place or will be executed immediately after aync or will the implementation be determined

Still asynchronous. It's just that the timer will be processed immediately after the function returns, and the JavaScript engine can handle events in the event loop.

+1
Nov 11 '14 at 23:22
source share

Recursion has many different definitions, but if we define it as intentional (as opposed to being caused by an error) using a function that repeatedly calls itself to solve a programming problem (which seems to be common in Javascript), it is absolutely true.

The real question is: can this lead to a browser crash. The answer is not in my experience ... at least not in Firefox or Chrome. Good practice or not, what you have is a fairly common Javascript template used in many real-time web applications. Notably, Twitter used something very similar to providing users with real-time updates (I doubt they are still doing this now when they use the Node server).

Also, from curious, I ran your script with a reset schedule to run every 50 ms and did not experience any slowdown.

0
Jan 03 '15 at 23:45
source share



All Articles