Loop through json with timeout variabe, javascript

Loop through json with timeout variabe, javascript

本文关键字:variabe javascript timeout with through json Loop      更新时间:2023-09-26

我在介绍我的基于网络的游戏时遇到了一些问题。它基本上是一个两个人使用语音气泡相互交谈的小场景。我决定使用 json 和 ES6 JavaScript。

我的 json 看起来像这样:

const script_scene1 = [
    {
        speaker: 'Ted',
        timer: 3000,
        emote: 'normal',
        quote: ''
    },
    {
        speaker: 'Ted',
        timer: 3000,
        emote: 'normal',
        quote: 'Bill, Bill? Where are you?'
    },
    {
        speaker: 'Bill',
        timer: 4000,
        emote: false,
        quote: 'Oh, Ted, I am lost. I think someone kidnapped me.'
    },
    {
        speaker: 'Ted',
        timer: 3000,
        emote: 'normal',
        quote: 'How did they kidnap you?'
    }
];

我的JS看起来像这样:

function playIntro() {
    let intro = document.getElementById("SceneOne");
    intro.style.display= "block";
    playScene(1, intro);
};
function playScene(scene) {
    let currentScript = getScript(scene);
    [].forEach.call(currentScript, function(subScript) {
            playSubScene(subScript);
    });
};
function playSubScene(script) {
    let speaker = script.speaker;
    let emote = script.emote;
    let quote = script.quote;
    let bubbles = document.querySelectorAll("speech");
    [].forEach.call(bubbles, function(bubble) {
        bubble.style.display = "none";
    });
    let bubble = document.getElementById(speaker);
    bubble.style.display = "block";
    bubble.innerHTML = quote;
};

我的 HTML 是这样的:

<section class="scene1" id="SceneOne">
    <button class="close-button" id="CloseButton">X</button>
    <div class="emoter1">
        <img src="images/ted.png" />
    </div>
    <div class="emoter2">
        <img src="images/bill.png" />
    </div>
    <article class="bubble pos1" id="Ted"></article>
    <article class="bubble pos2" id="Bill"></article>
    <article class="bubble pos3" id="RussetFive"></article>
    <article class="bubble pos4" id="DinkyPinky"></article>
</section>

现在,我想做的是循环遍历脚本中的拨号,以便每个字符依次说话,并且他们的文本显示给定的秒数(计时器值)。

我已经测试了setTimeout,但无济于事。我试图了解它如何与回调一起工作,但我还没有让它起作用。我也研究了承诺,但我真的不知道如何让它在一个循环中发挥作用。

当我有想法如何做到这一点时,这似乎很简单,但现在我已经卡了几个小时。

由于没有人回答,我想我会发布我自己的解决方案,即使它可能不是最漂亮的解决方案。

首先,我

说我正在使用一个json对象是错误的,它实际上是一个javascript对象。

我解决这个问题的方法是为每个对象创建一个计时器,其中将先前对象的时间添加到其中。也就是说,每行对话都有自己的计时器。

function playScene(scene) {
    let currentScript = getScript(scene);
    let currentTimer = 0;
    [].forEach.call(currentScript, function(element) {
        setTimeout(function() {
            playSubScene(element);
        }, currentTimer);
        currentTimer = currentTimer + element.timer;
    });
};