javascript - 循环第一次执行与下一次执行之间的延迟

标签 javascript for-loop delay

我正在尝试制作西蒙游戏,我快完成了,但遇到了问题。 在西蒙游戏中,当西蒙向您发出命令(由闪烁的灯光和每个灯光的音频表示)时,您需要记住并随后重复,每次闪烁(带有音频)与下一次闪烁之间会有短暂的延迟。

现在,我的西蒙正在发出声音,但它是同时发出所有声音,没有任何延迟。我尝试使用 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);
}

最佳答案

那么您想在每次 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");    
    }
});

这尚未经过测试,但应该可以工作,如果不行请告诉我。

关于javascript - 循环第一次执行与下一次执行之间的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47267156/

相关文章:

ios - 使用循环生成 uisegmentedcontrol 按钮

等待用户输入的javascript嵌套循环

verilog - #delay 如何用于 Verilog 非阻塞语句?

javascript - 防止 Android 中触摸事件出现延迟

javascript - 使用 Javascript DOM 删除 HTML 中的无序列表

javascript - 获取 api 时未调用 useEffect 且未更新状态

javascript - 我需要交易字段的文本作为通过 portlet 构建的 NetSuite 保存搜索中的变量

javascript - 蛇中的 SVG 动画

javascript - 循环确定数字的数字是否满足条件(Javascript)

javascript - 为什么我只从 javascript for 循环中获取最后一项?