Why Is My Loop Not Waiting Between Iterations? Settimeout()
I'm building a Simon says game http://codepen.io/meek/pen/adrbOv using jquery and I'm having some trouble with playing back each sound one by one. When the game starts, a list of 2
Solution 1:
setTimeout runs asynchronously, it is not blocking. If you want to wait for the timeout to finish, the next "loop iteration" needs to happen in the function callback you are giving setTimeout.
Something like this would work:
turn = 4;
var t = 1;
ourTimeout(allMovies, turn, t);
functionourTimeout(allMovies, turn, t){
AIbutton(allMoves[t-1]);
if(t <= turn)
setTimeout(ourTimeout(allMovies, turn, ++t), 1000);
}
@Alnitak mentions that this line of code:
setTimeout(ourTimeout(allMovies, turn, ++t), 1000);`
needs to be changed to this:
setTimeout(function(){
ourTimeout(allMovies, turn, ++t);
}, 1000);
As @Alnitak states, you can only pass an anonoymous or named function to setTimeout. The trick of passing variables is done as the change above mentions (concept is called a closure).
Post a Comment for "Why Is My Loop Not Waiting Between Iterations? Settimeout()"