My objective is to populate an array dynamically using setInterval function. So I created a global variable array that I can access outside the scope of setInterval function. But when I try to do console.log, its empty.
However, if I try to do console.log inside the setInterval function, I can see the array populating every 1000 ms.
Its supposed to be a global variable so i should be able to see the variable right? How come it cannot be seen outside the function?
below is the code:
var array = [];
var n;
setInterval(function(){
n = Math.random();
if(n < 0.5){
array.push('white');
}else{
array.push('black');
}
// console.log(array); // i can see the array here
}, 1000);
console.log(array); // but i cannot see the array here
UPDATE:
Ok I now know the reason why its empty. So when I put a setTimeout of 5secs, I can now see the contents.
setTimeout(function(){
console.log(array); // i can now see the array!
}, 5000);