-1

I want to display a live minutes:seconds countdown on the following webpage which upon reaching 00:00, shows an alert message saying "Time's Up!", and closes the window.

How do I do this?

Thanks for any help!

<html>
<head>
<title>Quiz!</title>
</head>

<body>
<font face="Helvetica" size="4">   
  <b> 
<center><h1>Sample Test 1 </h1></center>
<p><div id="quiz"></div>
<button id="submit">Get Results</button>
<div id="results"></div>
<script>
var myQuestions = [
    {
        question: "What is 10/2?",
        answers: {
            a: '3',
            b: '5',
            c: '115'
        },
        correctAnswer: 'b'
    },
    {
        question: "What is 30/3?",
        answers: {
            a: '3',
            b: '5',
            c: '10'
        },
        correctAnswer: 'c'
    }
];

var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');

generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);

function generateQuiz(questions, quizContainer, resultsContainer, submitButton){

    function showQuestions(questions, quizContainer){
        // we'll need a place to store the output and the answer choices
        var output = [];
        var answers;

        // for each question...
        for(var i=0; i<questions.length; i++){
            
            // first reset the list of answers
            answers = [];

            // for each available answer...
            for(letter in questions[i].answers){

                // ...add an html radio button
                answers.push(
                    '<label>'
                        + '<input type="radio" name="question'+i+'" value="'+letter+'">'
                        + letter + ': '
                        + questions[i].answers[letter]
                    + '</label>'
                );
            }

            // add this question and its answers to the output
            output.push(
                '<div class="question">' + questions[i].question + '</div>'
                + '<div class="answers">' + answers.join('') + '</div>'
            );
        }

        // finally combine our output list into one string of html and put it on the page
        quizContainer.innerHTML = output.join('');
    }


    function showResults(questions, quizContainer, resultsContainer){
        
        // gather answer containers from our quiz
        var answerContainers = quizContainer.querySelectorAll('.answers');
        
        // keep track of user's answers
        var userAnswer = '';
        var numCorrect = 0;
        
        // for each question...
        for(var i=0; i<questions.length; i++){

            // find selected answer
            userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;
            
            // if answer is correct
            if(userAnswer===questions[i].correctAnswer){
                // add to the number of correct answers
                numCorrect++;
                
                // color the answers green
                answerContainers[i].style.color = 'lightgreen';
            }
            // if answer is wrong or blank
            else{
                // color the answers red
                answerContainers[i].style.color = 'red';
            }
        }

        // show number of correct answers out of total
        resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
    }

    // show questions right away
    showQuestions(questions, quizContainer);
    
    // on submit, show results
    submitButton.onclick = function(){
        showResults(questions, quizContainer, resultsContainer);
    }

}
</script>
    
    
</body>
</html>
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • What exactly is the problem you are having in trying to do this? – FluffyKitten Jul 18 '20 at 03:14
  • Something like this? [how-to-measure-time-elapsed-js](https://stackoverflow.com/questions/31405996/find-elapsed-time-in-javascript) – F. Müller Jul 18 '20 at 03:26
  • Does this answer your question? [Find elapsed time in javascript](https://stackoverflow.com/questions/31405996/find-elapsed-time-in-javascript) – F. Müller Jul 18 '20 at 03:28
  • @FluffyKitten, I'm asking the question because, as a coincidence, I've already tried the article mentioned by F. Müller , and it doesn't actually show anything on the page. So, I've cleaned the file of that code and posted it here. – Sumukh Prasad Jul 18 '20 at 03:38
  • 2
    You still haven't explained what the **problem or error** is that you are having. Just telling us **"*I want this*" is not a coding problem**. This is not a coding or tutoring service. Please review [**How do I ask a good question**](https://stackoverflow.com/help/how-to-ask) and this [**Question Checklist**](https://meta.stackoverflow.com/questions/260648/) to see what is expected of you when you post a question here. – FluffyKitten Jul 18 '20 at 03:42
  • @FluffyKitten, thanks for the advice. Will try to improve my future questions. – Sumukh Prasad Jul 18 '20 at 06:01
  • @WebsiteCreator you can improve *this one* and have your question reopened :) – Al.G. Jul 18 '20 at 16:09

2 Answers2

0

You'll want to use setInterval

For example

let timeLeft = 60 * 2 // 2 minutes

let intervalId = setInterval(function() {
    --timeLeft
  let $time = document.getElementById('time')
  
  if (timeLeft === 0) {
    clearInterval(intervalId)
    $time.innerText = 'Times up!'
    return
  }
  
  let minutes = Math.floor(timeLeft/60)
  let seconds = timeLeft % 60
  $time.innerText = `${minutes}:${seconds.toString().padStart(2, '0')}`
}, 1000)
<!DOCTYPE html>
<html>
  <body>
    <p id="time"></p>
  </body>
</html>

Be warned - client-side timers can be spoofed by the user. If this is some form you're submitting to a server, then you might want to have the same timer running on the server that will reject requests after the time is up.

Scotty Jamison
  • 10,498
  • 2
  • 24
  • 30
0

You'll need the following element to display the remaining time:

<h5>30:00</h5>

And this async function:

const countdown = async () => {
  const startTime = Date.now();
  const halfHour = 1000 * 60 * 30;
  const endTime = startTime + halfHour;
  const display = document.querySelector('h5');
  display.innerHTML = '30:00';
  while (Date.now() < endTime) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    const timeRemaining = endTime - Date.now();
    const minutes = ~~(timeRemaining / (1000 * 60));
    const seconds = Math.round(timeRemaining / 1000) % 60;
    display.innerHTML = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }
  alert("Time's up!");
  window.open('', '_self').close();
}

You can see it live here:

<html>

  <head>
    <title>Quiz!</title>
  </head>

  <body>
    <font face="Helvetica" size="4">
      <b>
        <center>
          <h1>Sample Test 1 </h1>
          <h5>30:00</h5>
        </center>
        <p>
          <div id="quiz"></div>
          <button id="submit">Get Results</button>
          <div id="results"></div>
          <script>
            var myQuestions = [
              {
                question: "What is 10/2?",
                answers: {
                  a: '3',
                  b: '5',
                  c: '115'
                },
                correctAnswer: 'b'
              },
              {
                question: "What is 30/3?",
                answers: {
                  a: '3',
                  b: '5',
                  c: '10'
                },
                correctAnswer: 'c'
              }
            ];

            var quizContainer = document.getElementById('quiz');
            var resultsContainer = document.getElementById('results');
            var submitButton = document.getElementById('submit');

            generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);

            function generateQuiz(questions, quizContainer, resultsContainer, submitButton) {

              function showQuestions(questions, quizContainer) {
                // we'll need a place to store the output and the answer choices
                var output = [];
                var answers;

                // for each question...
                for (var i = 0; i < questions.length; i++) {

                  // first reset the list of answers
                  answers = [];

                  // for each available answer...
                  for (letter in questions[i].answers) {

                    // ...add an html radio button
                    answers.push(
                      '<label>'
                      + '<input type="radio" name="question' + i + '" value="' + letter + '">'
                      + letter + ': '
                      + questions[i].answers[letter]
                      + '</label>'
                    );
                  }

                  // add this question and its answers to the output
                  output.push(
                    '<div class="question">' + questions[i].question + '</div>'
                    + '<div class="answers">' + answers.join('') + '</div>'
                  );
                }

                // finally combine our output list into one string of html and put it on the page
                quizContainer.innerHTML = output.join('');
              }


              function showResults(questions, quizContainer, resultsContainer) {

                // gather answer containers from our quiz
                var answerContainers = quizContainer.querySelectorAll('.answers');

                // keep track of user's answers
                var userAnswer = '';
                var numCorrect = 0;

                // for each question...
                for (var i = 0; i < questions.length; i++) {

                  // find selected answer
                  userAnswer = (answerContainers[i].querySelector('input[name=question' + i + ']:checked') || {}).value;

                  // if answer is correct
                  if (userAnswer === questions[i].correctAnswer) {
                    // add to the number of correct answers
                    numCorrect++;

                    // color the answers green
                    answerContainers[i].style.color = 'lightgreen';
                  }
                  // if answer is wrong or blank
                  else {
                    // color the answers red
                    answerContainers[i].style.color = 'red';
                  }
                }

                // show number of correct answers out of total
                resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
              }

              // show questions right away
              showQuestions(questions, quizContainer);

              // on submit, show results
              submitButton.onclick = function () {
                showResults(questions, quizContainer, resultsContainer);
              }

            }

            const countdown = async () => {
              const startTime = Date.now();
              const halfHour = 1000 * 60 * 30;
              const endTime = startTime + halfHour;
              const display = document.querySelector('h5');
              display.innerHTML = '30:00';
              while (Date.now() < endTime) {
                await new Promise(resolve => setTimeout(resolve, 1000));
                const timeRemaining = endTime - Date.now();
                const minutes = ~~(timeRemaining / (1000 * 60));
                const seconds = Math.round(timeRemaining / 1000) % 60;
                display.innerHTML = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
              }
              alert("Time's up!");
              window.open('', '_self').close();
            }
            countdown();
          </script>
  </body>

</html>
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43