如何显示实时倒计时然后关闭 window?

How do I display a live countdown then close the window?

我想在以下网页上显示实时 minutes:seconds 倒计时,当到达 00:00 时,显示一条 alert 消息说 "Time's Up!",并关闭 window.

我该怎么做?

感谢您的帮助!

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

您需要使用 setInterval

例如

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>

请注意 - 客户端计时器可能会被用户欺骗。如果这是您要提交给服务器的某种形式,那么您可能希望服务器上有相同的计时器 运行,它会在时间到后拒绝请求。

您需要以下元素来显示剩余时间:

<h5>30:00</h5>

而这个 async 函数:

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();
}

你可以在这里看到:

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