I'm trying to log numbers to the console on specific intervals. However, what occurs instead is that it waits the set interval, then logs everything out as normal.
I've tried two different ways to create a closure both work. But do nothing in regards to the delayed console.log.
function timeOutLoop(x){
for(var i = 0; i<=x; i++){
(function(n){
setTimeout(function(){console.log(n)},5000)
})(i)
setTimeout(function(num){
return function(){
console.log(num)
}
}(i),1000)
}
}
timeOutLoop(33)
I was under the impression that each setTimeout will go on the event queue with the context provided by the closure. What gives?
forloop will finish up basically immediately; setting up each timer will take microseconds. They will then all wait either 1 or 5 seconds and all go off at the same time. It's like lighting the fuses of 33 firecrackers all at exactly the same time.