Reputation: 679
for(;i<5;i++)
{
(function(z){
setTimeout(function(){console.log(z);},2000);})(i);
}
This prints 0 1 2 3 4 5 at one shot after 2sec.Why is it so? and what is the solution to print each number after 2 sec.
Upvotes: 1
Views: 388
Reputation: 178350
Your timeouts needs to be spaced and I always use a different var to save each one in so I can clearTimeout on a specific one
var tIds=[];
for(var i=0;i<5;i++) {
(function(z){
tIds[i]=setTimeout(function(){window.console&&console.log(z);},2000*i); //fire 2000,4000,6000
})(i);
}
Also Please read the documentation to understand why 2000+i will not seem to work
Upvotes: 1
Reputation: 122956
setTimeout(fn,delay)
runs a given function fn
after delay delay
in ms. So you can simply multiply i
by 2000 and use:
for(;i<5;i++) {
setTimeout(function(){console.log(z);},2000*i);
}
If you want to report or use i
within fn
, you should create a function that returns a function for use in setTimeout
, using a closure to report or use i
. In the following i
is enclosed using the variable x
, used by the immediately invoked anonymous function creating the f
function Object for subsequent use in setTimeout
:
for(var i=0;i<5;i++)
{
var f = function(x){
return function(){console.log(z+'#'+x);}
}(i);
setTimeout(f,2000*i);
}
Upvotes: 0
Reputation: 1647
Try using this code.
//Referring your code for better understanding..
for(i=0;i<5;i++) {
(function(z){
setTimeout(function(){console.log(z);},2000*z);})(i);
}
Upvotes: 1
Reputation: 9622
setTimeout
won't block the execution of your code for 2 seconds. In fact setTimeout
returns immediately, and the loop continues. So all 5 of your async calls triggered at almost the same time after the timeout.
To approach what you want, I'd like this recursion-like version
function print(i) { if (i >= 5) return; console.log(i); setTimeout(function () { print(i + 1); }, 2000); } print(0);
Upvotes: 1
Reputation: 3243
you could try a diff approach using setInterval
,
var timer = setInterval(function(){printThing();},2000);
var i = 0;
function printThing(){
if(i<=5){
window.console && console.log(i);
++i;
}
else{
clearInterval(timer)
}
}//end function
heres an example http://jsfiddle.net/W9vS4/2/
Upvotes: 0
Reputation: 1944
You are firing 5 asynchronous , almost simultaneous, invocations of the function.
Upvotes: 1