Search code examples
javascripthtmlinputtimer

Creating a timer with user input with html and js


I am trying to create a simple timer, like the basic google one. I got it working until I tried to make it countdown from a value inputted by the user. I don't know why the code is no longer running. This is what I have so far:

<!DOCTYPE HTML>
<html>
  <body>
    <input id="userInput" type="number" defaultValue = "00"/> 
    <p id="timerr"> 00 </p>
    <button onclick="startTime()">Start time</button>
    <button onclick="stop()">Stop time</button>

    <script> 
      var myVar = setInterval(start, 1000);
      var timer = document.getElementbyId("userInput").value;

      function startTime(){ 

        document.getElementById("timerr").innerHTML = timer.value;
        myVar;
      } 

      function start(){
        document.getElementById("timerr").innerHTML = timer.value;
        timer.value--;
        if (timer == -1){
          stop();
          document.getElementById("timerr").innerHTML = "0";  
        }
      }

      function stop(){
        clearInterval(myVar);
      }
    </script>
  </body>
</html>

I am planning on making it better by making it countdown from minutes and hours, but I am just trying to get the seconds to function first. Thank you in advance.


Solution

  • Based on your current code structure, the following is a working version. Please check it.

    <!DOCTYPE HTML>
    <html>
      <body>
        <input id="userInput" type="number" value = "0"/> 
        <p id="timerr"> 00 </p>
        <button onclick="startTime()">Start time</button>
        <button onclick="stop()">Stop time</button>
    
        <script> 
          var myVar;
          var timer = document.getElementById("userInput");
          var countDownSeconds;
          function startTime(){ 
            myVar = setInterval(start, 1000);
            document.getElementById("timerr").innerHTML = timer.value;
            countDownSeconds = timer.value;
          } 
    
          function start(){
            countDownSeconds--;
            document.getElementById("timerr").innerHTML = countDownSeconds;
            if (countDownSeconds == -1){
              stop();
              document.getElementById("timerr").innerHTML = "0";  
            }
          }
    
          function stop(){
            clearInterval(myVar);
          }
        </script>
      </body>
    </html>