Simon Game, Javascript settimeout and animation

Simon Game, Javascript settimeout and animation

本文关键字:and animation settimeout Javascript Game Simon      更新时间:2023-09-26

谁能帮我模拟四个div标签的动画?简单的for循环应该等到div标签的不透明度在1秒内改变。

function animateDiv(ar) { // ar contains div tag indexes. ex:[0,3,2,3,1,0,1,2,3]
    for (var i = 0; i < ar.length; i++) {
        var ind = "";
        if (ar[i] == 0) ind = ".red";
        else if (ar[i] == 1) ind = ".blue";
        else if (ar[i] == 2) ind = ".yellow";
        else if (ar[i] = 3) ind = ".green";
        var ok = false;
        setTimeout(function () {
            $(ind).css('opacity', 1);
            console.log("waiting " + " index: " + i);
            ok = true;
        }, 1000);
        if (ok == true) {
            $(ind).css('opacity', 0.7);
            console.log("Done!");
        }
    }
}
https://jsfiddle.net/z8y2v5u1/

for循环不能等待超时完成,因为您提供给setTimeout()的函数在当前函数(以及调用当前函数的任何函数)完成后异步运行。因此,整个循环将在超时发生之前运行。

您需要使用依赖于setTimeout()的"伪循环"来触发下一次迭代。下面的代码可以工作:

function animateDivs(ar, cb) {
  var $divs = $(".red,.green,.blue,.yellow"),
    i = 0;
  (function next() {
    if (i === ar.length) {
      if (cb) cb();
    } else {
      var $div = $divs.eq(ar[i]).css('opacity', 1);
      setTimeout(function() {
        $div.css('opacity', 0.7);
        i++;
        next();
      }, 1000);
    }
  })();
}
animateDivs([0,3,2,3,1,0,1,2,3], function() { console.log("Finished")});
div { width: 40px; height: 40px; display: inline-block; opacity: 0.7;}
.red { background-color: red;}
.green { background-color: green;}
.blue { background-color: blue;}
.yellow { background-color: yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red"></div><div class="green"></div>
<br/>
<div class="blue"></div><div class="yellow"></div>

next()函数将适当的div更改为不透明度1,然后使用setTimeout()在更改不透明度之前等待一秒钟,然后再次调用next()以获取数组中的下一个索引。

我认为你可能想知道动画何时结束,所以我添加了一个回调参数(cb)到animateDivs(),它将在整个数组被处理后被调用-在我的例子中,它所做的只是将一些东西记录到控制台,但你可以用它来做一些更有趣的事情。