As long as your approach is valid, it cannot be used if you have an indefinite number of calls, since each chain in your async command is hard-coded.
If you want to apply the same functionality in an array, it is best to provide a function that creates an internal function and applies a timeout on its internal function:
var asyncArraySequence = function (array, callback, done){ var timeout = 1000, sequencer, index = 0; // done is optional, but can be used if you want to have something // that should be called after everything has been done if(done === null || typeof done === "undefined") done = function(){} // set up the sequencer - it similar to your `func` sequencer = function(){ if(index === array.length) { return done(); } else { callback(array[index]); index = index + 1; setTimeout(sequencer, timeout); } }; setTimeout(sequencer, timeout); } var arr = [1,2,3]; asyncArraySequence(arr, function(val){console.log(val);});
source share