倒计时延迟JavaScript

问题描述 投票:1回答:4

我已经开始学习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

请帮我解决这个问题。

javascript settimeout delay
4个回答
1
投票

你可以使用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>

1
投票

您可能误解了如何使用闭包以及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>

1
投票

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

0
投票

如果你使用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>
© www.soinside.com 2019 - 2024. All rights reserved.