Reputation: 852
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?
Upvotes: 2
Views: 187
Reputation: 879
function timeOutLoop(x){
for(let i = 0; i<=x; i++){
setTimeout(function(){console.log(i)},i * 1000);
}
}
timeOutLoop(33);
Is this what you are looking for? Change from var
to let
in order to keep the variable i
intact inside the loop scope. More here about let vs var.
Also multiply i
by 1000 to print every second until reaching 33.
Upvotes: 1
Reputation: 1435
Since the loop basically executed instantly, with the first one there will not be much of a difference since the time is in milliseconds and as for the second one, they will all execute after 1 second.
Using a combination of the two methods, you can achieve it:
function timeOutLoop(x) {
for(var i = 0; i <= x; i++) {
setTimeout(function(num) {
return function(){
console.log(num);
}
}(i), i * 1000);
}
}
timeOutLoop(33)
Upvotes: 2
Reputation: 689
setTimeouts start at the same time so if you want to start a timeout after another you can create a recursive function :
function timeOutLoop(x, i=0){
if(i<=x){
console.log(i);
i++;
setTimeout(function(){timeOutLoop(x, i)},1000);
}
}
timeOutLoop(33)
You can set timeout value to whatever you like.
Upvotes: 2