Search code examples
javascriptsettimeoutdelay

Countdown with a delay in JavaScript


I've started to learn JavaScript, and I'm coding a program that get a number from the user and counts down to zero with a delay of one second for each number.

This is my code:

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>

I used setTimeout and setInterval, but my problem is that it just shows zeros for each number, like this:

0, 0, 0, 0

Please help me to solve this problem.


Solution

  • You can use setTimeout() with 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>