Search code examples
javascripthtmlcountdowntimer

How to Change the display of countdown?


I have made a countdown with password protection. So this is my code

var myTimer;
   function clock() {
     myTimer = setInterval(myClock, 1000);
     var c = 180;
     var pass1 = 12;
     var input = document.getElementById("userInput").value;
     
     
     
     function myClock() {
       if (input==pass1){
       
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
       }
     }
   }
<p id="demo">180</p>


<form id="form" onsubmit="return false;">
  <input type="password" id="userInput" />
  <br/>
  <input type="submit" onclick="clock()" value="Start"/>
  <button onclick="clearInterval(myTimer)">Stop counter</button>
</form>

And this is the result.

enter image description here

But i dont like like that. I want to change into minutes. So 180 will be 3 minutes 0 seconds. And still countdown until 0 minute 0 second. How to change it?


Solution

  • This can be achieved by small modifications in existing code. You need to calculate mins and remaining seconds from seconds. Refer following code sample.

    const mins = Math.floor(c / 60);
    const remainingSecs = c % 60;
    

    Integrating everything:

    var myTimer;
    
    function clock() {
      myTimer = setInterval(myClock, 1000);
      var c = 180;
      var pass1 = 12;
      var input = document.getElementById("userInput").value;
    
      function myClock() {
        if (input == pass1) {
          c = parseInt(c);
          if (!isNaN(c) || c > 0) {
            c--;
            const mins = String(Math.floor(c / 60)).padStart(2, '0');
            const remainingSecs = String(c % 60).padStart(2, '0');
            document.getElementById("demo").innerHTML = `${mins}:${remainingSecs}`;
            if (c === 0) {
              clearInterval(myTimer);
              alert("Reached zero");
            }
          }
        }
      }
    }
    <p id="demo">Timer will appear here</p>
    
    
    <form id="form" onsubmit="return false;">
      <input type="password" id="userInput" />
      <br />
      <input type="submit" onclick="clock()" value="Start" />
      <button onclick="clearInterval(myTimer)">Stop counter</button>
    </form>

    String.prototype.padStart()