function asyncForEach(array,cb) {
array.forEach(function(i){
setTimeout(cb(i),0);
});
}
asyncForEach([1,2,3,4], function(i) {
console.log(i);
});
console.log("After loop");
The result of the above snippet as you would see is
1
2
3
4
After loop
What I expected was
After loop
1
2
3
4
What I thought would happen is that function asyncForEach would be added to the call stack, and for each element in array, callback in setTimeout would be pushed to callback queue. Console.log("After loop"); would be printed and call stack would then get empty, following which all the callbacks would execute one by one. But that doesn't seem to be the case. Can anyone explain ?
Thanks.