首页 > 解决方案 > 测验计时器 JavaScript

问题描述

任何人都可以检查此代码并查看我哪里出错了。测验应该给你 1 分钟的时间来回答问题。如果用户及时完成测验,它应该显示重置按钮并停止计时器。如果用户随后单击重置按钮,则测验应以重新启动的计时器重新启动。

如果计时器用完,测验会显示重置按钮。

感谢您提供正确方向的任何指示。

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let shuffledQuestions, currentQuestionIndex

var timeInMinutes = 1;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);

function getTimeRemaining(endtime){
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime){
  var clock = document.getElementById(id);
  function updateClock(){
    var t = getTimeRemaining(endtime);
    clock.innerHTML = t.minutes + ':' + t.seconds;
    if(t.total<=0){
      clearInterval(timeinterval);
      startButton.innerText = 'Restart'
      startButton.classList.remove('hide')
    }
  }
  
  updateClock(); // run function once at first to avoid delay
  var timeinterval = setInterval(updateClock,1000);
}

startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
  currentQuestionIndex++
  setNextQuestion()
})

function startGame() {
  currentTime = Date.parse(new Date());
  deadline = new Date(currentTime + timeInMinutes*60*1000);
  console.log(new Date, deadline) 
  initializeClock('clockdiv', deadline);
  startButton.classList.add('hide')
  shuffledQuestions = questions.sort(() => Math.random() - .5)
  currentQuestionIndex = 0
  questionContainerElement.classList.remove('hide')
  setNextQuestion()
}

function setNextQuestion() {
  resetState()
  showQuestion(shuffledQuestions[currentQuestionIndex])
}

function showQuestion(question) {
  questionElement.innerText = question.question
  question.answers.forEach(answer => {
    const button = document.createElement('button')
    button.innerText = answer.text
    button.classList.add('btn')
    if (answer.correct) {
      button.dataset.correct = answer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
  })
}

function resetState() {
  clearStatusClass(document.body)
  nextButton.classList.add('hide')
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

function setStatusClass(element, correct) {
  clearStatusClass(element)
  if (correct) {
    element.classList.add('correct')
  } else {
    element.classList.add('wrong')
  }
}

function clearStatusClass(element) {
  element.classList.remove('correct')
  element.classList.remove('wrong')
}

const questions = [
  {
    question: 'What is 2 + 2?',
    answers: [
      { text: '4', correct: true },
      { text: '22', correct: false }
    ]
  },
  {
    question: 'Who is the best YouTuber?',
    answers: [
      { text: 'Web Dev Simplified', correct: true },
      { text: 'Traversy Media', correct: true },
      { text: 'Dev Ed', correct: true },
      { text: 'Fun Fun Function', correct: true }
    ]
  },
  {
    question: 'Is web development fun?',
    answers: [
      { text: 'Kinda', correct: false },
      { text: 'YES!!!', correct: true },
      { text: 'Um no', correct: false },
      { text: 'IDK', correct: false }
    ]
  },
  {
    question: 'What is 4 * 2?',
    answers: [
      { text: '6', correct: false },
      { text: '8', correct: true }
    ]
  }
]
*, * ::before, *::after {
    box-sizing: border-box;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}

:root {
    --hue-neutral: 200;
    --hue-wrong: 0;
    --hue-correct: 145;
}

body{
font-size: 2rem;
--hue: var(--hue-neutral);
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
text-align: center;
justify-content: center;
align-items: center;
background-color: hsl(var(--hue), 100%, 20%);
}


body.correct {
    --hue: var(--hue-correct);
}

body.wrong {
    --hue: var(--hue-wrong);
}

.container{
    width: 800px;
    max-width: 80%;
    background-color: white;
    border-radius: 5px;
    padding: 10px;
    box-shadow: 0 0 10px 2px;
}

.btn-grid{
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 10px;
    margin: 20px 0;
}

.btn{
    font-size: 2rem;
    --hue: var(--hue-neutral);
    border: 1px solid hsl(var(--hue), 100%, 30%);
    background-color: hsl(var(--hue), 100%, 50%);
    height: 50px;
    border-radius: 5px;
    padding: 5px 10px;
    color: white;
    outline: none;
}

.btn:hover{
    border-color: black;
}

.btn-correct {
    --hue: var(--hue-correct);
    color: black;
}

.btn-wrong {
    --hue: var(--hue-wrong);
}

.start-btn, .next-btn{
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
}

.score-btn{
    background-color: coral;
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
}

.controls{
    display: flex;
    justify-content: center;
    align-items: center;
}

.hide {
    display: none;
}

.titlecontainer{
    margin-bottom: 30px;
    margin-top: 30px;
    font-size: 2rem;
}

#time{
    color: red;
    justify-content: left;
    text-align: left;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link href="styles.css" rel="stylesheet">
  <script defer src="script.js"></script>
  <title>Quiz App</title>
</head>
<body>
  <div class="container">
    <div id="clockdiv"></div>
    <div id="question-container" class="hide">
      <div id="question">Question</div>
      <div id="answer-buttons" class="btn-grid">
        <button class="btn">Answer 1</button>
        <button class="btn">Answer 2</button>
        <button class="btn">Answer 3</button>
        <button class="btn">Answer 4</button>
      </div>
    </div>
    <div class="controls">
      <button id="start-btn" class="start-btn btn">Start</button>
      <button id="next-btn" class="next-btn btn hide">Next</button>
    </div>
  </div>
</body>
</html>

标签: javascripthtml

解决方案


如我所见,问题是测验完成后倒计时不会停止。由于函数 initializeClock 中的这一行,倒计时工作

var timeinterval = setInterval(updateClock,1000);

所以你应该做的就是用

clearInterval(timeinterval)

当测验结束时。但问题是——您无法从 initializeClock 函数之外达到可变的“时间间隔”。解决这个问题的最简单方法是:

  1. 在全局范围内声明“时间间隔”。
  2. 在 selectAnswer 函数中进行一些更改,如下所示:
function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (shuffledQuestions.length > currentQuestionIndex + 1) {
    nextButton.classList.remove('hide')
  } else {
    // THESE ARE THE OLD 'ELSE' INSTRUCTIONS:
        // startButton.innerText = 'Restart'
    // startButton.classList.remove('hide') 

    // HERE BELOW ARE NEW:
    clearInterval(timeinterval) // clear current countdown
    startButton.innerText = 'You finished, restart?'// Little text mod
    startButton.classList.remove('hide') //this is exactly from old version
  }
}

推荐阅读