循环首次执行与下一次执行之间的延迟

时间:2017-11-13 14:52:54

标签: javascript for-loop delay

我试图制作一个西蒙游戏而且我差不多完成但是我遇到了问题。 在一个西蒙游戏中,当西蒙给你你需要记住并随后重复的顺序(由闪烁的灯和每个灯的音频表示)时,每次闪烁之间会有短暂的延迟(用它和#39; s audio)到下一个。

所以现在,我的西蒙正在发出声音,但它一下子就完成了所有声音,没有任何延迟。我尝试使用setIntarvelsetTimeout但仍然可以同时播放所有音频。

因为添加眨眼不应该是那么难以保持到最后。

然后我建立了一个计时器功能:

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
        }
}

在播放音频的功能中使用它,但它仍在做同样的事情 - 一次播放它。

这是负责音频的功能:

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

这个功能负责游戏的逻辑:

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;    //For timer()

function randomSimon() {
var randomBtn = btns[Math.floor(Math.random() * 4)];
randomOrder += randomBtn;
for  (i = 0; i <= randomOrder.length - 1; i++) {
    for (s = 0; s <= i; s++) {
        var someText = "";
        someText += randomOrder.charAt(s);
        playAudio(randomOrder.charAt(s));
        document.getElementById('debug').innerHTML = someText; //this is for debugin, should be ignored.
        timer(500);
    }
}

}

这是更好阅读的整个脚本:

var isGameStarted = false;

var d = new Audio("dSharpNote.wav");
var a = new Audio("aSharpNote.wav");
var g = new Audio("gSharpNote.wav");
var c = new Audio("cNote.wav");

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;

function startGame() {
    isGameStarted = true;         //So players won't be able to just press the simon's buttons.
    randomOrder = "";             //A variable to keep the random order given by the simon.
    playerInputOrder = "";        //A variable to keep the random order the player inputs.
    randomSimon();                //Called to give the first button in the order.
}

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
            playAudio(randomOrder.charAt(s));
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.
            timer(500);
        }
    }
}

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
    }
}

function playerProgress(btn) {                        //Getting the player's input and checks if it's in the right order.
    if (isGameStarted == true) {
        var btnClicked = btn.id;                      //Gets the id of the button the player clicked.
        playAudio(btnClicked);                        //So this could play it's audio.
        playerInputOrder += btnClicked;
        if (playerInputOrder.length == randomOrder.length) {
            if (playerInputOrder == randomOrder) {
                playerInputOrder = "";
                setTimeout(randomSimon, 1000);
            } else {
                document.getElementById('scoreText').innerHTML = randomOrder + " Game Over!";
                isGameStarted = false;               //Makes the player unable to play the simon's button's audios.
            }
        }
        document.getElementById('debug').innerHTML = playerInputOrder;
    }
}

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

function someInterval() {
    var i = 0;
    var anInterval = setInterval(function() {
        i++;
        if (i > 11) {
            clearInterval(anInterval);
            timer *= 2;
        }
    }, timer);
}

2 个答案:

答案 0 :(得分:1)

所以你想在每次playAudio调用后暂停一下?

我还会继续超时

var sounds = {};
sounds.a = ...;
sounds.b = ...;

function playAudio(sound, callback) {
    if (typeof sounds[sound] === "undefined") {
        throw "sound not available";
    }
    sounds[sound].play();
    if (typeof callback !== "undefined") {
        window.setTimeout(callback, 500);
    }
}

// play a - pause - b - pause c
playAudio("a", function(){
    playAudio("b", function() {
        playAudio("c");
    });
});

如果您首先构建序列,那么也可以动态

var sequence = ["a", "b", "c"];
var pointer = 0;

playAudio(sequene[pointer], function() {
    pointer += 1;
    if (typeof sequence[pointer] !== "undefined") {
        playAudio(sequence[pointer], this); // this will be bound to the function itself
    } else {
        alert("sequence finished");    
    }
});

这未经过测试,但应该可以使用,如果没有,请告诉我。

答案 1 :(得分:1)

您可以使用setTimeout并在浏览颜色时将其增加:

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
  >>>>>>>   setTimeout(function() { playAudio(randomOrder.charAt(s)); },2000*s);
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.

        }
    }
}

这将立即播放第一个声音,2秒后播放第二个声音,4秒后播放第三个声音,依此类推。希望它有所帮助!

修改

您有一个for循环和setTimeout的示例:

&#13;
&#13;
for (s = 0; s <= 2; s++) {
  setTimeout(function() { console.log('hello world'); },2000*s);
}
&#13;
&#13;
&#13;

编辑2

好的,内存访问似乎在这里搞乱了。试着这样做。

首先创建一个函数,在等待后执行您想要执行的操作:

var delayedPlay = function(c,delay) {
  setTimeout(
    function() { playAudio(c); },
    delay);
}

然后在for循环中调用它:

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
  >>>>>>>   delayedPlay(randomOrder.charAt(s),2000*s);
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.

        }
    }
}