Search code examples
javascripthtmltimeunix-timestamp

Show Date.getTime() javascript into html


I am trying to make a stopwatch using html and javascript on my website. Here is what I tried:

<!DOCTYPE HTML>
<html>
  <script>
    Date.setTime(0);
  </script>
  <body>
    <p>Time: <script>document.write(Date.getTime());</script></p>
  </body>
</html>

I want it to show milliseconds since load. I'm doing it on KhanAcademy. Does anybody know how to do this?

Also, somewhat, weirdly, there are no errors


Solution

  • If you want to show the milliseconds since the page load you need to update it using setInterval()

    <!DOCTYPE HTML>
    <html>
      
      <body>
        <p>Time: <span id="msec"></span> </p>
      </body>
      
      
      <script>
    
        var msec = 0;
        
        msec = setInterval(function(){
            msec = msec + 1;
            
            document.getElementById("msec").innerText = msec;
        },1)
    
      </script>
    </html>