Rock
Rock

Reputation: 758

How to add setTimeout function for the Foreach loop

Hi want to set the timeout funtion for the Freach loop for the callback i am setting the timeout funtion. but its displaying Undifined error. can anybody Explain me here is My code.

function async(array,cb){

    array.forEach(function () {
        setTimeout(cb,0);

    })

}

async([1,2,3,4],function(i){
    console.log(i);
});

Upvotes: 2

Views: 1085

Answers (1)

jcubic
jcubic

Reputation: 66518

Try:

function async(array,cb){
    array.forEach(function(e) {
        setTimeout(function() { cb(e); },0);

    });
}

async([1,2,3,4,5], function(i) {
  console.log(i);
});

Upvotes: 3

Related Questions