JSFiddle - React, Tailwind, and code Playground

by Nicolaus 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>

JavaScript

const qElem = document.querySelector('#question');
qElem.textContent =
      'What is the largest planet in the Solar System?';

const tElem = document.querySelector('#time');
startTimer(30, tElem, function() {
  alert("Time's up!");
});
https://jsfiddle.net/Zombo/hbxgnusg/2/#


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);
        elem.textContent = seconds;
        if (seconds <= 0) {
          clearInterval(timer);
          endHandler();
        }
    }, 1000);
}