为什么我的setTimeout()在执行回调函数时会在屏幕上返回一个随机数

问题描述 投票:0回答:1

我正在尝试通过构建一个测验应用程序来学习 Svelte。

我想要实现的是,当用户回答了测验中的一个问题时,它会自动跳转到下一个。我将

setTimeout()
设置为 1 秒,以便用户在被引导到下一个问题之前有一点时间看看他是否回答正确。

这可行,但我发现每次运行

toNextQuestion()
函数时,它都会在屏幕上打印一个随机数值,就像添加到 DOM 中一样。

我谷歌了一下,似乎

setTimeout()
函数会返回一个数字值作为其 ID。但我可以在这里绕过它吗?

在没有将随机数添加到 DOM 的情况下,我应该怎么做才能实现目标?

我的代码是这样的:

<script>
    const toNextQuestion = () => {
        currentQ uestionIndex += 1;
        correct = undefined;
        questionAnswered = false; 
    };
</script>

  {#await promise}
    <p>...waiting</p>
  {:then data}
    <h1>Question {currentQuestion} of {data.results.length}</h1>
    <em>Score: {score}</em>
    {#each data.results as questionData, index}
        {#if index === currentQuestionIndex}
            <Question
                {questionData}
                {questionAnswered}
                {answerQuestion}
                {evaluateAnswer}
            />
        {/if}
    {/each}

    {#if questionAnswered}
        {setTimeout(() => {toNextQuestion()}, 1000)}
        <!-- Here it would add a random number TODO -->

    {/if}

    {#if currentQuestionIndex == data.results.length - 1}
         <!-- Here for completing the quiz TODO -->
    {/if}
{/await}

如有任何建议,我们将不胜感激!非常感谢!

javascript dom svelte settimeout
1个回答
0
投票

将其包裹在 IIFE 中,即

(() => ...)()

{#if questionAnswered}
    {(() => setTimeout(() => {toNextQuestion()}, 1000))()}
{/if}
© www.soinside.com 2019 - 2024. All rights reserved.