Using Javascript i need to be able to:
1: Push a certain amount of the same function (with a different parameter in each) into an array.
2: Then run each functio
First of all you are not pushing functions into the array at the moment, you execute the func instead. To achieve the push your func should look like this:
// Function for array objects - alert passed parameter
function func(num){
return function(){
alert(num);
}
}
Now if your functions are synchronous you could simply iterate over the array
for(var i in arr){
arr[i]();
}
console.log('done');
If we are dealing with asynchronous functions then they need to have a callback:
// Function for array objects - alert passed parameter
function func(num){
return function(callback){
alert(num);
callback();
}
}
And then you can either use a counter to run in parallel.
var count = arr.length;
for(var i in arr){
arr[i](function(){
if(--count === 0){
console.log('Done');
}
});
}
Or in sequence:
function run(){
var fn = arr.shift();
if(!fn){
console.log('Done');
} else {
fn(run);
}
}
run();