Gimana ya cara start, stop sama reset stopwatch ini pake keydown event?

<script>
let output = document.getElementById('stopwatch');
let ms = 0;
let sec = 0;
let min = 0;

function timer() {
    ms++;
    if(ms >= 100){
        sec++
        ms = 0
    }
    if(sec === 60){
        min++
        sec = 0
    }
    if(min === 60){
        ms, sec, min = 0;
    }

    //Doing some string interpolation
    let milli = ms < 10 ? `0`+ ms : ms;
    let seconds = sec < 10 ? `0`+ sec : sec;
    let minute = min < 10 ? `0` + min : min;

    let timer= `${minute}:${seconds}:${milli}`;
    output.innerHTML =timer;
};
//Start timer
function start(){
 time = setInterval(timer,10);
}
//stop timer
function stop(){
    clearInterval(time)
}
//reset timer
function reset(){
    ms = 0;
    sec = 0;
    min = 0;

    output.innerHTML = `00:00:00`
}

</script>
avatar mustofaaaaaaaaaaaa
@mustofaaaaaaaaaaaa

1 Kontribusi 0 Poin

Diperbarui 3 tahun yang lalu

Tanggapan

Pertanyaan kamu tidak jelas, coba dijelaskan lebih baik. Jangan hanya copy paste kode ya

bisa pake library mousetrap https://craig.is/killing/micehttps://craig.is/killing/mice kalo ga mau ribet

1 Jawaban:

<div>Coba ini:</div><pre>&lt;html&gt; &lt;head&gt; &lt;title&gt;Stopwatch Javascript&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 id="stopwatch"&gt;00:00:00&lt;/h1&gt;

&lt;button onclick="start()" id="start"&gt;Start&lt;/button&gt; &lt;button onclick="stop()" id="stop" disabled&gt;Stop&lt;/button&gt; &lt;button onclick="reset()" id="reset" disabled&gt;Reset&lt;/button&gt; &lt;script&gt; let output = document.getElementById('stopwatch'); let btnstart = document.getElementById("start"); let btnstop = document.getElementById("stop"); let btnreset = document.getElementById("reset"); let ms = 0; let sec = 0; let min = 0;

function timer() { ms++; if(ms &gt;= 100){ sec++ ms = 0 } if(sec === 60){ min++ sec = 0 } if(min === 60){ ms, sec, min = 0; }

//Doing some string interpolation
let milli = ms &amp;lt; 10 ? `0`+ ms : ms;
let seconds = sec &amp;lt; 10 ? `0`+ sec : sec;
let minute = min &amp;lt; 10 ? `0` + min : min;

let timer= `${minute}:${seconds}:${milli}`;
output.innerHTML =timer;

}; // Start timer function start(){ time = setInterval(timer,10); btnstop.removeAttribute("disabled"); btnstart.setAttribute("disabled", ""); btnreset.setAttribute("disabled", ""); } // stop timer function stop(){ clearInterval(time); btnreset.removeAttribute("disabled"); btnstart.removeAttribute("disabled"); btnstop.setAttribute("disabled", ""); } // reset timer function reset(){ ms = 0; sec = 0; min = 0;

output.innerHTML = `00:00:00`

} &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre><div><br><strong>Semoga membantu</strong></div>

avatar syahid246
@syahid246

70 Kontribusi 160 Poin

Dipost 3 tahun yang lalu

Login untuk ikut Jawaban