Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 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 20 sounds ("moves") is generated, which will play one by one each turn. So if the moves list is [ 'red', 'yellow', 'green'], on turn one 'red' will play, on turn two 'red' and 'yellow' will play, and so on.

I've set the turn to 4 and I'm trying to get each sound to play one after the other, until 4 sounds are played. I'm using this code:

turn = 4;
var t = 1;
  while(t <= turn) {
    setTimeout(AIbutton(allMoves[t-1]), 1000);
    t++;
  }

AIbutton() is the function that plays a sound (simulates a button press) and allMoves is the list of 20 moves that will play throughout the game. What I want for it to happen is that a sound is played on each iteration of the loop before moving onto the next iteration, but what happens is that all the sounds in the loop iterates over play at the same time after an interval of 1000 ms.

I thought the setTimeout would make it so it pauses between iterations? How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

function ourTimeout(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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...