0

For synchronization (to serialize execution) I often use recursive functions in javascripts.

For an example to serialize the execution of following code,

var array = [1,2,3,4,5,6,7,8,9];
//total delay 1s (1s for all)
for (var i=0; i<array.length; i++){
    (function(i){
         setTimeout(function(){console.log(array[i])},1000);
    })(i);
}

I use recursive code like this,

var array = [1,2,3,4,5,6,7,8,9];
//total delay 10s (1s for each)
var i = 0;
function fn(){
    setTimeout(function(){console.log(array[i])
        i++;
        if (i<array.length){
            fn();
        }
    },1000);

}
if (array.length > 0){
    fn();
}

Even though in many programming languages, recursive functions have issues with stack overflow, I don't see that drawback here unless we don't use return statements.

My question is, What are the pros and cons of using recursive functions for synchronization in javascripts?

Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40
  • 6
    It's not really recursion; it just *looks like* recursion. – Pointy Nov 04 '14 at 22:13
  • Could you explain it more? – Sampath Liyanage Nov 04 '14 at 22:18
  • Seems like the commenter on your other answer already did: http://stackoverflow.com/questions/26744175/how-to-delay-a-for-loop-in-jquery/26744341#comment42074879_26744341 –  Nov 04 '14 at 22:22
  • Those codes produce different results. The first one produces all the output (almost) at the same time, the second one produces it step by step. – Oriol Nov 04 '14 at 22:23
  • 1
    It's not recursion because you do: `fn() -> sleep -> fn()`. It would be if you did: `fn() -> i++, i fn()`. – istos Nov 04 '14 at 22:23

1 Answers1

4

Real recursion involves functions that call themselves directly or indirectly. This is a recursive function:

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

Your code, however, merely arranges for the system to (sometimes) call your function again some time in the future. By the time that function call happens, the original function call will have finished. (It finishes basically immediately after setting up the timeout.) Thus, at any given time, there's only one call to the function in progress, so there won't be any issues with running out of stack space.

Pointy
  • 405,095
  • 59
  • 585
  • 614