简体   繁体   English

foreach循环的每次迭代之间的延迟?

[英]Delay between each iteration of foreach loop?

so I am making a simon says game. 所以我正在制作一个西蒙说游戏。 This function displays the current sequence. 此功能显示当前序列。 The problem with it right now is that it doesn't really go in a nice sequence, it kind of does everything at once. 它现在的问题在于它并没有真正顺利进行,它可以同时完成所有事情。 Say the colors are "blue", "red", and "yellow, they will all go off at the same time rather than in sequence. How can I fix this? 说颜色是“蓝色”,“红色”和“黄色,它们会同时发生而不是按顺序发生。我该如何解决这个问题?

var displaySequence = function(){
    compSequence.forEach(function(color){
        $("#" + color).fadeTo(300, 0.5).fadeTo(300, 1.0);
    })
}

A none jQuery solution. 一个没有jQuery的解决方案。 You will need to use the array index to give the illusion of waiting between each call, however each function has ran already. 您将需要使用数组索引来给出每次调用之间等待的假象,但是每个函数已经运行。 What will happen is: show color 1 in 1 second, show color 2 in 2 seconds... 会发生什么:1秒内显示颜色1秒,2秒内显示颜色2 ...

var displaySequence = function(){
    compSequence.forEach(function(color, index){
        setTimeout(function(){
            $("#" + color).fadeTo(300, 0.5).fadeTo(300, 1.0);
        },
        1000 * index);
    })
}

adjust the 1000 * index to change the delay. 调整1000 *索引以更改延迟。

I make use of the jQuery delay function 我使用了jQuery 延迟函数

Here is a the javascript. 这是一个javascript。

$(document).ready(function(){

  var compSequence = new Array("red", "blue", "yellow");

  var displaySequence = function() {

      $.each(compSequence, function (i, color) {
        // add delay
        $("#" + color).delay(i * 1000).fadeTo(300, 0).fadeTo(300, 1.0);
      });      
  }

  displaySequence();

});

Here is a DEMO 这是一个DEMO

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

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