0

I'm trying to make a terminal quiz that has a timer running in the background while you answer the question, which, once finished, overrides the input if it hasn't been filled.

I've tried putting the timer and question into different functions and have called them in different orders:

const prompt = require("readline-sync");
let countdown;

function timer(questionAnswer){
    clearTimeout(countdown);
    countdown = setTimeout(() => {
        console.log("Sorry! you ran out of time. The answer was " + questionAnswer);
    }, 5000);//<-- Adjust this number to change the length of the countdown

}

function question(questionAnswer){
    let playerAnswer = prompt.question("Please enter your answer:   ");
    playerAnswer = Number(playerAnswer);//<--change this line depending on variable type

    if(countdown != 0){
        if(playerAnswer == questionAnswer){// change this condition on a question-by-question basis
          console.log("Correct!");
          //<--add point distribution here
        }else{
            console.log("Incorrect! The correct answer was " + questionAnswer);
        }  
    clearTimeout(countdown);
    }
}

question(72);//<¬
timer(72);// <----Change these lines to read from a file that stores the answers depending on the question

However, calling the timer first has no effect and continues straight to the question, and if I call the question first, the timer only starts after the input has been filled.

2
  • 5
    readline-sync is synchronous. prompt.question blocks all other code until it returns. "Is there a way to have the timer override the prompt input?" No. Are you looking for terminal user interface (TUI)? Commented Sep 23 at 12:16
  • @jabaa (no reliable way but control characters can work. Nostalgic for spinning cursors today…😂) Commented Sep 23 at 13:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.