function format(n) { return (n < 10 ? "0" + n : n); }
var hour,min,sec,ms;
function timer() {
if ((millisecond += 1) == 100) {
millisecond = 0;
second++;
}
if (second == 60) {
second = 0;
minute++;
}
if (minute == 60) {
minute = 0;
hour++;
}
hour = format(hour);
min = format(minute);
sec = format(second);
ms = format(millisecond);
}
I'm using this piece of code to generate timestamps. Check how is the output:
00:00:00.01
00:00:00.02
...
00:00:10.10
00:00:10.11
00:00:10.12
...
00:02:05:01
00:02:05:02
...
It works perfectly! But, I'm using setTimeout and this is very innacurate sometimes. So, my idea is start working with Date.Now(), but when I use it, I got something like this as response:
00:00:00.02
00:00:00.05
00:00:00.07
...
00:00:07.17
00:00:00.21
00:00:00.23
...
It works, but I'm unable to catch every millisecond and second, and this won't fit my need! So, what should I do? Here is the code:
var offset = 0,
paused = true;
render();
function startStopwatch(evt) {
if (paused) {
paused = false;
offset -= Date.now();
render();
}
}
function stopStopwatch(evt) {
if (!paused) {
paused = true;
offset += Date.now();
}
}
function resetStopwatch(evt) {
if (paused) {
offset = 0;
render();
} else {
offset = -Date.now();
}
}
function format(value, scale, modulo, padding) {
value = Math.floor(value / scale) % modulo;
return value.toString().padStart(padding, 0);
}
var min, sec, ms;
function render() {
var value = paused ? offset : Date.now() + offset;
ms = format(value, 1, 1000, 3);
sec = format(value, 1000, 60, 2);
min = format(value, 60000, 60, 2);
if(!paused) {
requestAnimationFrame(render);
}
}
Thank you!