为什么我的循环在迭代之间不等待?setTimeout() [英] Why is my loop not waiting between iterations? setTimeout()

查看:59
本文介绍了为什么我的循环在迭代之间不等待?setTimeout()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个西蒙说游戏 http://codepen.io/meek/pen/adrbOv 使用jquery,我在逐个播放每个声音时遇到了一些麻烦.

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.

游戏开始时,将生成20种声音(动作")的列表,这些声音将每回合一声播放.因此,如果移动列表为['red','yellow','green'],则在转弯处将播放一个红色",在转弯处将播放两个红色"和黄色",依此类推.

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.

我将转数设置为4,我试图让每种声音依次播放,直到播放4种声音为止.我正在使用此代码:

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()是播放声音(模拟按钮按下)的函数,而 allMoves 是将在整个游戏中播放的20种动作的列表.我想要实现的是在循环的每次迭代之前播放声音,然后再进行下一次迭代,但是发生的是循环中的所有声音在间隔1000毫秒之后同时迭代播放.

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.

我以为setTimeout可以做到,所以它可以在两次迭代之间暂停?我该如何实现?

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

推荐答案

setTimeout异步运行,它不会阻塞.如果要等待超时结束,则需要在提供setTimeout的函数回调中进行下一次循环迭代".

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.

类似的事情会起作用:

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 提到这行代码:

@Alnitak mentions that this line of code:

setTimeout(ourTimeout(allMovies, turn, ++t), 1000);`

需要更改为此:

setTimeout(function(){
        ourTimeout(allMovies, turn, ++t);
    }, 1000);

如@Alnitak所述,您只能将一个匿名或命名函数传递给setTimeout.传递变量的技巧是通过上述更改完成的(概念称为闭包).

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

这篇关于为什么我的循环在迭代之间不等待?setTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆