实现Timer-Javascript的困难

时间:2016-07-19 17:49:48

标签: javascript html timer

我一直在尝试为我正在研究的这个Trivia游戏实现一个计时器,但我不明白它在我的情况下会如何工作。我有以下代码:

JS:

    var questions = [
{
  "question": "The next Playstation platform will be:",
  "allAnswers": ["PS5", "PS4K", "PSX", "PS8K"],
  "correctAnswer": "PS4K"
},
{
  "question": "The Sloth's scientific name, Bradypus, is Greek for:",
  "allAnswers": ["Moving slowly", "Swiftly", "Slow feet", "Sleeping"],
  "correctAnswer": "Slow feet"
},
{
  "question": "Earth is how far away from the Sun:",
  "allAnswers": ["92.96 Million Miles", "82.96 Million Miles", "102.96 Million Miles", "72.96 Million Miles"],
  "correctAnswer": "92.96 Million Miles"
},
{
  "question": "The first issue of National Geographic was issued in:",
  "allAnswers": ["1901", "1874", "1888", "1926"],
  "correctAnswer": "1888"
},
{
  "question": "It is approximitely how hot on the planet Venus:",
  "allAnswers": ["262 Degrees C", "162 Degrees C", "462 Degrees C", "862 Degrees C"],
  "correctAnswer": "462 Degrees C"
},
{
  "question": "What type of star is the Sun:",
  "allAnswers": ["White Dwarf", "Yellow Dwarf", "The sun is NOT a star", "Orange Dwarf"],
  "correctAnswer": "Yellow Dwarf"
},
{
  "question": "Approximitely how much of the ocean has been explored:",
  "allAnswers": ["12%", "23%", "38%", "5%"],
  "correctAnswer": "5%"
},
{
  "question": "Approximitely how long did it take for the Apollo missions to reach the moon:",
  "allAnswers": ["36 hours", "24 hours", "72 hours", "96 hours"],
  "correctAnswer": "72 hours"
},
{
  "question": "The world record for most spoons balanced on the face is:",
  "allAnswers": ["45 spoons", "62 spoons", "31 spoons", "91 spoons"],
  "correctAnswer": "31 spoons"
},
{
  "question": "The world record for most socks put on one foot in one minute is:",
  "allAnswers": ["12 socks", "28 socks", "48 socks", "67 socks"],
  "correctAnswer": "48 socks"
}];

var content = document.getElementById("content");
var questionHolder = document.getElementById("question");
var choicesHolder = document.getElementById("choices");
var scoreHolder = document.getElementById("score");
var timeHolder = document.getElementById("time");
var submitButton = document.getElementById("submit");

var questionTracker = 0;
var score = 0;
var timer = 20;
var wasQuestionAsked = true;

// var myTimer = setInterval(askQ(), 10000);

function askQ()
{
  var choices = questions[questionTracker].allAnswers;
  var tempChoices = "";

  for(var i = 0; i < choices.length; i++)
  {
    tempChoices += "<input type='radio' name='quiz" + questionTracker + "' id='choice" + (i + 1) + "' value='" + choices[i] +
     "'>" + " <label for='choice" + (i + 1) + "'>" + choices[i] + "</label><br>";
  } 

  /* LOAD UP QUESTIONS */
  questionHolder.textContent = "Question: " + (questionTracker + 1) + ". " + questions[questionTracker].question;
  timeHolder.textContent = "Time: " + timer + " seconds left.";
  /* LOAD UP ANSWERS */
  choicesHolder.innerHTML = tempChoices;
  tim = setTimeout(askQ(), 1000);

  /* SETUP, FIRST ITERATION */
  if(questionTracker == 0)
  {
    scoreHolder.textContent = "Score: 0 correctly answered questions out of " + questions.length + " total questions.";
    // timeHolder.textContent = "Time: " + timer + " seconds left."; 
    submitButton.textContent = "Submit Q";
  }
}

function validateAnswer()
{
  /* CHECK IF QUESTION WAS ASKED, DETERMINE IF WE PROCEED TO NEXT QUESTION */
  if(wasQuestionAsked)
  {
    submitButton.textContent = "Next Q";
    wasQuestionAsked = false;

    /* DETERMINE WHICH RADIO BUTTON WAS CLICKED */
    var userSelection, correctIndex;
    var radios = document.getElementsByName("quiz" + questionTracker);
    for(var i = 0; i < radios.length; i++)
    {
      /* IF RADIO BUTTON IS CHECKED */
      if(radios[i].checked)
      {
        userSelection = radios[i].value;
      }

      /* FIND CORRECT INDEX */ 
      if(radios[i].value == questions[questionTracker].correctAnswer)
      {
        correctIndex = i;
      }
    }

    var labelChange = document.getElementsByTagName("label")[correctIndex].style;
    labelChange.fontWeight = "bold";
    if(userSelection == questions[questionTracker].correctAnswer)
    {
      score++;
      labelChange.color = "#33cc00";
    }
    else
    {
      labelChange.color = "#cc0000";
    }

    scoreHolder.textContent = "Score: " + score + " correctly answered questions out of " + questions.length + " possible.";
    /* MOVE ON TO NEXT QUESTION */
  }
  else
  {
    wasQuestionAsked = true;
    /* RESET BUTTON TEXT TO "SUBMIT QUESTION" */
    submitButton.textContent = "Submit Q";
    /* IF WE HAVE NOT YET REACHED LAST QUESTION, INCREASE Q BY ONE */
    if(questionTracker < questions.length - 1)
    {
      questionTracker++;
      askQ();
    }
    else
    {
      showFinalScore();
    }
  }
}

/* FUNCTION THAT WILL DISPLAY THE SCORE ONCE TRIVIA GAME IS OVER */
function showFinalScore()
{
  content.innerHTML = "<h2 style='color:orange;'>You've finished the Trivia Game!</h2>" + "<h2 style='color:orange;'>These are your results:</h2>" +
   "<h2 style='color:orange;'>" + score + " out of a total of " + questions.length + " questions." + "<br>" + "Your percentage was: " + Math.round(score / questions.length * 100) +
    "%</h2>" + "<br>" + "<button class='btn btn-warning' onclick='reset()'>Restart</button>";
}

/* FUNCTION THAT WILL RESET THE GAME */
function reset()
{
  location.reload();
}

window.addEventListener("load", askQ, false);
submitButton.addEventListener("click", validateAnswer, false);

还有一些HTML:

<div id="content">
                <h3 id="question" style="color:orange;">

                </h3>
                <div id="choices">

                </div>
                <br>
                <p><button id="submit" class="btn btn-warning"></button>
                </p>

                <p id="score">

                </p>
                <p id="time">

                </p>
              </div>

我想要的只是当一个问题出现时出现一个计数器,并从20开始倒计时。我一直在检查W3的setInterval()和setTimeout(),但似乎无法使它们工作正确。如果有人可以查看代码并帮助我,以及任何提示/帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

以下是一个例子:

<!-- output timer - this will be updated every second. -->
<div id="output-timer" style="position: absolute; top: 0%; left: 0%;">
</div>

<script>
    // This is a recursive function, if intTimer is 0 it will return
    // without doing anything...if intTimer > 0 it will:
    //
    //    1. decrease the timer.
    //    2. update the output.
    //    3. call itself...
    //
    function updateTimer(intTimer) {
        // timer has expired.
        //
        if (intTimer == 0)
            return;

        setTimeout(function() {
            // Decrease timer...
            //
            intTimer--;

            // Update the output...
            //
            document.getElementById('output-timer').innerHTML = intTimer.toString();

            // Next.
            //
            updateTimer(intTimer);
        }, 1000);
    }

    // Initialise the timer ad begin timing!
    //
    function initTimer(intTimer) {
        document.getElementById("output-timer").innerHTML = intTimer.toString();

        updateTimer(intTimer);
    }

    initTimer(20);
</script>