Обратный отсчет с задержкой в ​​JavaScript - PullRequest
0 голосов
/ 13 сентября 2018

Я начал изучать 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>

Я использовал setTimeout и setInterval, но моя проблема в том, что он просто показывает нули для каждого числа, например:

0, 0, 0, 0

Пожалуйста, помогите мне решить эту проблему.

Ответы [ 4 ]

0 голосов
/ 13 сентября 2018

Я бы сделал это с 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>
0 голосов
/ 13 сентября 2018

Возможно, вы неправильно понимаете, как использовать замыкание вместе с 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>
0 голосов
/ 13 сентября 2018

С помощью 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 голосов
/ 13 сентября 2018

Вы можете использовать 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>
...