Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...