简体   繁体   中英

Stopwatch in Javascript is slower than normal time

I want to make a stopwatch in JavaScript that could count milliseconds, seconds and minutes. This is what I have: (you can stop the timer by pressing space)

 var counter = document.getElementsByTagName('h1')[0]; var miliseconds = 0; var seconds = 0; var minutes = 0; function Add() { miliseconds++; if (miliseconds >= 99) { miliseconds = 0; seconds++; if (seconds >= 59) { seconds = 0; minutes++; } } counter.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds ? (seconds > 9 ? seconds : "0" + seconds) : "00") + ":" + (miliseconds ? (miliseconds > 9 ? miliseconds : "0" + miliseconds) : "00"); Timer(); } function Timer() { t = setTimeout(Add, 10); } Timer(); document.addEventListener("keypress", function(e) { if (e.keyCode === 32) { clearTimeout(t); } }); 
 <h1 id="counter">00:00:00</h1> 

The problem is that it seems to not go at the proper speed, meaning that when I compare it to other timers, it gradually becomes slower than them (ie the speed at which the timer is counting slows down over time). So suddenly, there are 5-second differences, then it becomes 7-second differences and so on. Any help would be appreciated.

You should create a startTime variable, then calculate the elapsedTime , and use that to calculate additional variable to show.

var startTime = Date.now();
setTimeout(function(){
    var elapsedTime = Date.now() - startTime;
    // Additional code to calculate hour, minute, second, milisecond here
}, 10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM