r/coding • u/Intrepid_Composer_84 • May 23 '22
Simple Stopwatch Using JavaScript
https://www.codemediaweb.com/2022/05/simple-stopwatch-using-javascript.html[removed] — view removed post
0
Upvotes
r/coding • u/Intrepid_Composer_84 • May 23 '22
[removed] — view removed post
1
u/bibamann May 23 '22 edited May 23 '22
Yeahhh... and here is, how it's done correctly:
You create a new Date() when the timer starts (so you when you hit the start button)
You add the timeout (like 5 Minutes) to it and store the timestamp
On the setInterval callback you create a new Date(), get its timestamp and substract it from the initial one to get the milliseconds still to go.
Out of this result you can recreate the minutes, seconds and ms for the display
And why?
Because setInterval() isn't exact. When you set it to like 100 it doesn't mean the callbacks happen exactly every 100ms but more likely on 105, 110, 102 and so on. So the countdown gets incorrect VERY fast (like ~5 seconds / minute).
And don't care about creating a new Date() every 50ms - the cpu / browsers etc. can handle this very well (ok, you shouldn't do it on animationFrame - but you also don't need it).
Best regards
A guy who created several countdowns in his life and ran into this trap, too ;)