JSFiddle - React, Tailwind, and code Playground

by Chris Maloney

HTML

<h1>Here are a couple Questions to try out:</h1>
<h2>Question #1</h2>
  <h3>Question</h3>
    <div id='question'></div>
    <h3>Answer</h3>
    <textarea id='answer'></textarea>
<div id='time'></div>
<div id='timeup'></div>

JavaScript

// this will be a big array.
const questionsAndAnswers = [
  { q: 'What is the largest planet in the Solar System?',
    a: 'Fred', },
  { q: '... next question ...',
    a: '... next answer ...' },
];

const currentQuestion = 0;
const qElem = document.querySelector('#question');
const tElem = document.querySelector('#time');

startTimer(5, tElem, function() {
  qElem.textContent = questionsAndAnswers[currentQuestion].q;
});

// this will check the answer
function __endHandler() {   
  // Now, here, we want to read what the user typed in, and compare that with the correct answer.
  //const ansElem = document.querySelector('#answer');
  //const yourAnswer = ansElem.textContent;
  console.log('Hey, handsome!');
  //alert('You typed an answer!');
}


function startTimer(duration, elem, endHandler) {
    const start = Date.now();
    const end = start + duration * 1000 + 9;
    const timer = setInterval(function () {
        const timeLeft = end - Date.now();
        const seconds = Math.floor(timeLeft / 1000);
        console.log('tick');
        elem.textContent = seconds;
        if (seconds <= 0) {
          console.log('about to clearInterval');
          clearInterval(timer);
          console.log('done clearInterval, calling endHandler');
          __endHandler();
          console.log('done endHandler')
          document.querySelector('#timeup').textContent = 'Time is Up!';
        }
    }, 1000);
}