Possible Duplicate:
How to Use setTimeout in a for…loop
calling setTimeout with a for loop
For me, setTimeout function doesn't work inside for loop. It executes after all for loop statements are executed.
I am facing with this scope issue in case of setTimeout function in javascript.
Here's my code snippet ..
... moves[] is an array ..
for(i=0;i<noOfMoves;i++) {
playerName = moves[i].playerName;
timeDiff = moves[i].timeDiff;
console.log("Inside for loop"+ playerName);
setTimeout(function(){
console.log("Inside set time out :"+playerName);
},timeDiff);
....
....
}
But it awkwardly prints out the following output ...
Inside for loopplayer1
Inside for loopplayer2
Inside for loopplayer3
Inside for loopplayer4
.... (noOfMoeves times .. )
Inside set time outplayer1
Inside set time outplayer1
Inside set time outplayer1
Inside set time outplayer1
EDIT :
I am wanting o/p of following way
I am expecting the code to go line by line .. printing "Inside for loop" console log first, then wait for "timeDiff" period and then print the "Inside settimeout" function console log .. how can i do that ? –
Inside for loopplayer1
Inside set time outplayer1 // (after waiting for timeDiff time)
Inside for loopplayer2
Inside set time outplayer2 // (after waiting for timeDiff time)
......
......
Also, playerName variable is getting same value in each settimeout console log statement ?