简体   繁体   English

暂停动画执行

[英]Pausing execution for animation

I am making a simple Simon Says game for practice, but I am having a little trouble. 我正在制作一个简单的Simon Says游戏进行练习,但是遇到了一些麻烦。

When the AI plays out the pattern that the user is to imitate, I want it to press the buttons one at a time. 当AI播放出用户要模仿的模式时,我希望它一次按下一个按钮。 There needs to be a little pause between each button press to allow for the sound and animation to complete. 每按一次按钮之间需要稍作停顿,以使声音和动画完成。

I am storing the pattern in an array, and using a for loop to cycle through it, like this: 我将模式存储在数组中,并使用for循环遍历它,如下所示:

var computerPattern = [1, 2, 3, 4];

for (i=0; i<computerPattern.length; i++){
    setTimeout(function() {
        switch(computerPattern[i]) {
            case 1:
                    beep($("#green"));
                    break;
            case 2:
                    beep($("#red"));
                    break;
            case 3:
                    beep($("#blue"));
                    break;
            case 4:
                    beep($("#yellow"));
                    break;
            default:
                    break;
        }
    }, 250);
}
// Where 'beep' is a function that plays a sound and animation.

As you can see, I am using setTimeout because that's what I've been able to find throught my research. 如您所见,我正在使用setTimeout因为这是我在整个研究过程中都能找到的。 But it's not working, so maybe my whole approach is wrong. 但是它不起作用,所以也许我的整个方法是错误的。

I would appreciate any suggestions as to how to go about this. 我将对如何解决此问题提出任何建议。

Your code won't work regardless of the delay because the name i in your function is bound to the variable i in the enclosing environment. 无论延迟如何,您的代码都将无法工作,因为函数中的名称i与封闭环境中的变量i绑定在一起。 This is very important: the name i does not capture the value of i at the time you define the function. 这一点非常重要:在定义函数时,名称i不会捕获i的值。 It refers to the variable i that was declared before the function definition. 它引用在函数定义之前声明的变量i By the time the first timeout fires, the value of i will be 4. Thus, all four timeout functions will use an incorrect value. 到第一个超时触发时, i的值将为4。因此,所有四个超时函数将使用错误的值。

There are several ways to solve your problem. 有几种方法可以解决您的问题。 Here is a simple one: 这是一个简单的例子:

var colors = ['green', 'red', 'blue', 'yellow'],
    position = 0;

function flash() {
  beep($('#' + colors[position]));
  if (++position < colors.length) {
    window.setTimeout(flash, 250);
  }
}

flash();

If you want to have a delay of 250 milliseconds before the first beep, replace the last line above with this: 如果要在第一声蜂鸣声之前延迟250毫秒,请使用以下命令替换上面的最后一行:

window.setTimeout(flash, 250);

One more observation: you don't really need jQuery here. 另一个观察结果:您在这里实际上并不需要jQuery。 You could write: 您可以这样写:

beep(document.getElementById(colors[position]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM