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?