I don't see the need of recursion here, if you want to return a function then re-run the function you can use setTimeout depending on the framework, will work just fine in browsers.
var index = 0;
function iterArray(arr, index){
if(arr && index <= arr.length ){
index++;
setTimeout( fucntion(){iterArray(arr, index);^, 10 ); // Index is a global var, why you're passing it?
return (arr[index]);
}
}
This will continue the recursion but will return just the first match. To do what you're trying to accomplish by your example, the best way AFAIK is to mimic a class:
function nextIndexContainer( arrayToStore ){
// Make a copy so it doesn't get changed on the fly, or remove the JSON's if this behaviour is desireable
this.array = JSON.parse( JSON.stringify( arrayToStore ) );
this.index = 0;
this.next = function(){
if( this.array[ this.index ] )
return this.array[ this.index++ ];
else
return 'Last index reached';
}
}
To use it:
var arrIndex = new nextIndexContainer([1, 5, 8]);
console.log(arrIndex.next()); // '1'
console.log(arrIndex.next()); // '5'
console.log(arrIndex.next()); // '8'
console.log(arrIndex.next()); // 'Last index reached'
return (arr[index]);maybe...?retvalue and function logic?returnwill not execute.