倒计时 JavaScript

Countdown with a delay in JavaScript

我已经开始学习 JavaScript,我正在编写一个程序,从用户那里获取一个数字并倒数到零,每个数字延迟一秒。

这是我的代码:

function DescreasNo(){
    var MyInput = parseInt(document.getElementById('HoursOfWork').value);
 var output = document.getElementById('output01');
 output.innerHTML = '';
 for ( var i=MyInput ; i>0 ; i--){
        output.innerHTML += i +"<br>";
    } 
}
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="StyleSheet.css" />
    <script src="Script.js"></script>


    <title>EyeProctect Project</title>
</head>
<body>
 <h1>Eye Protect</h1>
    <h4>Keep Your Eyes safe</h4>
    <input type="text"  id="HoursOfWork" placeholder="Enter your hours of work ...." />
    <button class="start" onclick="DescreasNo()" >Let's Go!</button>
    <p id="output01"></p>

   
</body>
</html>

我使用了 setTimeoutsetInterval,但我的问题是它只为每个数字显示零,如下所示:

0, 0, 0, 0

请帮我解决这个问题。

您可以将 setTimeout() 与 IIFE 一起使用:

function DescreasNo(){
  var MyInput = parseInt(document.getElementById('HoursOfWork').value);
  var output = document.getElementById('output01');
  output.innerHTML = '';

  (function loop (i) {          
    setTimeout(function () {   
      output.innerHTML += i +"<br>";            
      if (--i) loop(i); // call the function until end
    }, 1000); // 1 second delay
  })(MyInput);
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text"  id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>

您可能误解了如何将闭包与 setTimeout(或 setInterval)一起使用。

function decreaseNumber() {
    const total_hours = parseInt(document.getElementById('HoursOfWork').value);
    const output_div  = document.getElementById('output01');
    let current_hour  = total_hours;

    const countdown = () => {
        output_div.innerHTML += current_hour + "<br />";

        if (--current_hour > 0) {
            setTimeout(countdown, 1000); // 1000 milliseconds
        }
    };

    countdown();
}
<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="StyleSheet.css" />
        <script src="Script.js"></script>
        <title>EyeProctect Project</title>
    </head>
    <body>
        <h1>Eye Protect</h1>
        <h4>Keep Your Eyes safe</h4>
        <input id="HoursOfWork" placeholder="Enter your hours of work ...." />
        <button class="start" onclick="decreaseNumber()">Let's Go!</button>
        <p id="output01"></p>
    </body>
</html>

使用 setInterval 你可以这样做。

function DescreasNo(){
  var MyInput = parseInt(document.getElementById('HoursOfWork').value);
  var output = document.getElementById('output01');
  output.innerHTML = '';

  var countDown = MyInput;
  var intervalId = setInterval(function () {   
      output.innerHTML += countDown +"<br>";            
      if (--countDown <= 0) 
        clearInterval(intervalId); // clear timer when finished
    }, 1000); // 1 second delay between decrements
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text"  id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>

我会使用 setInterval 执行此操作,如果您使用 parseFloat 而不是 parseInt,则可以允许小数小时。您还可以相当轻松地设置秒数的格式以提供良好的读数。

你也应该小心清除间隔,以防有人在倒计时期间多次按下按钮,否则你会得到多个计时器。在这里,如果你按两次它会重置它。

一些改进包括验证输入以确保它是一个数字:

let int;
function DescreasNo() {
    clearInterval(int)  // clear interval to allow button to reset counter
    var MyInput = document.getElementById('HoursOfWork').value;
    let seconds = (parseFloat(MyInput) * 60 * 60)
    var output = document.getElementById('output01');
  
    int = setInterval(() => {
      if (seconds <= 0) {  // finished
        clearInterval(int)
        return
      }
      output.innerHTML = formatTime(seconds--)
    }, 1000)
  }
  
  function formatTime(seconds) {
    let hours = Math.floor(seconds / (60 * 60)).toString().padStart(2, '0')
    let minutes = Math.floor((seconds - hours * 3600) / 60).toString().padStart(2, '0');
    let second = Math.floor(seconds - (hours * 3600) - (minutes * 60)).toString().padStart(2, '0');
    return `${hours}:${minutes}:${second}`;
  }
<h1>Eye Protect</h1>
  <h4>Keep Your Eyes safe</h4>
  <input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
  <button class="start" onclick="DescreasNo()">Let's Go!</button>
  <p id="output01"></p>