I make a JS stopwatch that has format H:m:s:ms when it reached 60 min it always increase to 61,62 and so on
i am using setInterval here is my code:
n = 3600;
td = setInterval(function ()
{
n ;
let hours = parseInt(n / 3600);
var m = parseInt(n / 60)
var s = parseInt(n / 60 % 60);
var M = parseInt(n % 60);
// let hours = Math.floor(((n[ids] / 1000) / 60) / 60) % 24
// let m = Math.floor((n[ids] / 1000) / 60) % 60
// let s = Math.floor(n[ids] / 1000) % 60
// let M = Math.floor(n[ids] % 1000)
$("#display0").html(toDub(hours) ":" toDub(m) ":" toDub(s) ":" toDub(M))
}, 1000 / 60);
full source code: https://jsfiddle.net/greycat/danvL42s/2/
I am sure there is something wrong with my m variable.
Anyone can help me out?
CodePudding user response:
The logic follows that a second is the rounded value for its fraction of 60 milliseconds, and a minute is the rounded value for its fraction of 60 seconds, so on and so forth.
You can refactor the time variables as below:
var M = parseInt(n % 60);
var s = parseInt(n / 60 % 60);
var m = parseInt(n / 60**2 % 60);
var hours = parseInt(n / 60**3 % 60);
CodePudding user response:
function toDub(n){
return n < 10 ? "0" n : "" n
}
$(document).on('click', '.start01', function(event) {
$(this).attr("style", "display:none");
var ids = parseInt($(this).attr('id').substring(5));
$("#stop" ids).attr("style", "display:block")
// console.log(n[ids])
n = 0;
td = setInterval(function ()
{
n ;
let hours = parseInt(n / 216000);
var m = parseInt(n / 3600)
var s = parseInt(n / 60 % 60);
var M = parseInt(n % 60);
// let hours = Math.floor(((n[ids] / 1000) / 60) / 60) % 24
// let m = Math.floor((n[ids] / 1000) / 60) % 60
// let s = Math.floor(n[ids] / 1000) % 60
// let M = Math.floor(n[ids] % 1000)
$("#display0").html(toDub(hours) ":" toDub(m) ":" toDub(s) ":" toDub(M))
}, 1000 / 60);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="">
<h2 style="margin:0px auto;">tim 1</h2>
<div style="margin:0px auto;">
<h1 id="display0">00:00:00:00</h1>
</div>
<div style="margin:0px auto;">
<div >
<div role="group" aria-label="Basic outlined example"><button type="button"
style="display:block" id="start0"><i ></i>
start</button>
<button type="button" style="display:none"
id="stop0"><i ></i> pause</button>
<br><button type="button"
id="reset0"><i ></i> reset</button></div>
</div>
</div>
</div>
CodePudding user response:
n =0;
td = setInterval(function ()
{
n ;
let hours = parseInt(n / 3600000);
var m = parseInt(n 600000 / 60000)
var s = parseInt(n 600000 `000/ 1000);
var M = parseInt(n 600000 `000% 1000);
$("#display0").html(toDub(hours) ":" toDub(m) ":" toDub(s) ":" toDub(M));
if(m==60){
n=0;
}
}, 1);