When attempting to log numbers at specific intervals on the console, I encountered an unexpected issue. Instead of logging each number after a set interval, all numbers are logged out simultaneously.
I've experimented with two different approaches to create a closure, both of which seem to work but fail to address the delayed console.log problem.
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 believed that each setTimeout would enter the event queue with the context provided by the closure. What could be causing this unexpected behavior?