Vanilla JS Stopwatch Issue

Hi friends! I made this stopwatch using vanilla JavaScript, and for some reason, it resets (to zero) at one second on first run. It works as expected on second run, but could someone explain the issue and point me in the right direction to fixing it? Thank you!

https://codepen.io/brianamorganbooks/pen/zYrONey

1 Like

I tried it. That doesn’t happen to me. I think it’s the time load from codepen. Did you try this on localhost?

Yes, it looks like codepen problem as it doesn’t seemed to happen in Full View mode.

The way you produce time is somewhat incorrect though. When user hits “start” button you need to timestamp that moment with Date.now() and then in your interval check how much time left, not to produce time, every 10ms. Setting interval in 10ms absolutely doesn’t guarantee this precision, in fact it’s almost certainly will go off! On other hand, when you checking time the fact the Timer is off a bit will not affect real time - no one will ever notice jump from “42” centiseconds to “44”, right?

UPDATE: One extra advantage of such approach that you don’t have to fire interval every 10ms as well, but let’s say every 16ms (60FPS) - this seems like not a big deal but for browser is actually quite a good news and browser will be much happier :slight_smile: