Reputation: 7121
This code waits one second and executes all the iterations at once:
for(let i=0;i<4;i++){
setTimeout(function(){console.log("Hello")},1000)
}
This code executes properly as expected:
var i = 0;
function loop(){
setTimeout(function(){
console.log("Hello" + " " + Number(i+1))
i++
if(i<3){
loop()
}
},1000)
loop()
My question is why? Does this have to do with the synchronous single-threaded nature of JavaScript? how so? An explanation as to why this is happening is my question.
Upvotes: 0
Views: 49
Reputation: 288100
You probably want to multiply the delay by i
var f = function(){console.log("Hello")};
for (let i=0; i<4; ++i) setTimeout(f, i * 1000);
Upvotes: 0
Reputation: 324630
Your first code does this:
"Set four timeouts to go off in one second from now"
Your second code is:
"Set a timeout and alert the value of i
, increment i
and if the loop isn't over then set a new timeout"
Quite a difference! The key thing is, setting multiple timeouts isn't like a queue, they will all start from when you call them.
Upvotes: 4