|
> this resulted in 51.0s being displayed as 1:51 What? > with rounding up it's even worse resulting in 1:01:51 Huh? If you are making some kind of timer, you first should convert the time to pure seconds, or in whatever the smallest unit is that you care to deal with (milliseconds?). It is only at that point that the data is ready for any kind of arithmetic (for example, to subtract 1 second). Then, when you wish to display it, you first convert it. For example, if the user sets your timer to 2 minutes, you would convert "2:00" to 120 seconds. Then you subtract 1 second. Now the internal value is 119. Then you convert back to the display format: "1:59". But be sure to keep "119" in some internal variable, for the next change. <form name=f>
<input type=number name=h min=0 max=99 value=0>
<input type=number name=m min=0 max=59 value=00>
<input type=number name=s min=0 max=59 value=00>
<input type=submit value=Start>
<output name=r></output>
</form>
<script>
document.forms.f.addEventListener('submit', function (ev) {
ev.preventDefault();
let f = ev.target,
s = Number(f.h.value * 60 * 60) +
Number(f.m.value * 60) +
Number(f.s.value);
function show(f, s) {
let h = Math.floor(s / 60 / 60);
s -= (h * 60 * 60);
let m = Math.floor(s / 60);
s -= (m * 60);
m = String(m).padStart(2, '0');
s = String(s).padStart(2, '0');
f.elements.r.value = [h, m, s].join(':');
}
show(f, s);
if (f.timer) { clearInterval(f.timer); }
f.timer = setInterval(function () {
if (0 === s) { clearInterval(f.timer); return; }
s -= 1;
show(f, s);
}, 1000);
});
</script>
|