0

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

Sascha
  • 4,576
  • 3
  • 13
  • 34
Lucas Urban
  • 627
  • 4
  • 15

3 Answers3

1

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>
0

You likely meant to do this

NOTE the script tags have to be AFTER the span - it needs to exist.

let d = new Date();
d.setTime(1000)
const span = document.getElementById("time");
const tId = setInterval(function() {
  if (d.getTime() <= 0) clearInterval(tId);
  span.textContent = d.getTime();
  d.setTime(d.getTime() - 10)
}, 10); 
<span id="time"></span>

but that is the same as doing this

let d = 1000;

const span = document.getElementById("time");
const tId = setInterval(function() {
  span.textContent = d-=10
  if (d <= 0) clearInterval(tId);
}, 10)
<span id="time"></span>

Using the window load event so the script can stay in the head

Herre I am counting up

window.addEventListener("load", function() { // on page load
  let d = 0;

  const span = document.getElementById("time");
  const tId = setInterval(function() {
    span.textContent = d += 10
    if (d >= 1000) clearInterval(tId);
  }, 10);
  
});
<span id="time"></span>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You have to set an interval to update calculate the duration since starting the website (I choose 1 ms). The script has to be written in the code after the HTML-element is declared.

var start = performance.now();

setInterval(function() {
    let time = performance.now();
  document.getElementById('duration').innerHTML = 'Dauer: ' + (time - start) + ' ms.';
}, 1);
 <div id='duration'></div>
Sascha
  • 4,576
  • 3
  • 13
  • 34