Search code examples
javascriptdomsveltesettimeout

Why would my setTimeout() return a random number on screen when the callback function executed


I am trying to learn Svelte by building a quiz app.

What I wanted to achieve is that when the user has answered a question from the quiz, it automatically jumps to the next one. I set a setTimeout() of 1 second so the user has a bit of time to see if he has answered correctly or not before being directed to the next question.

This works but I find that every time the toNextQuestion() funtion runs, it would print a random number value on screen, like being added to DOM.

I google and it seems that a setTimeout() funtion would return a number value as its ID. but can I bypass it here?

What should I do to achieve the goal while not having a random number added to DOM?

My code is like:

<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}

Any advice would be appreciated ! Thank you so much!


Solution

  • Wrap it in an IIFE i.e. (() => {})()

    {#if questionAnswered}
        {(() => {
            const timerId = setTimeout(() => {
                toNextQuestion();
            }, 1000);
            // Do not return anything...
        })()}
    {/if}
    

    This way you have a void function call, but why are you trying to render this in the DOM in the first place?