Learn to create simple stopwatch with html, css and javascript.
HTML
<div class="container"> <div class="timer"> <div class="timer_container"> <span id="hour">00</span><span>:</span> <span id="minute">00</span><span>:</span> <span id="second">00</span><span>:</span> <span id="millisecond">00</span> </div> </div> <div class="btn"> <button id="btnStart">Start</button> <button id="btnReset">Reset</button> </div> </div>
CSS
html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } body { padding: 0; margin: 0; } .container { width: 600px; height: 330px; margin: 80px auto; } .timer { width: 100%; margin-top: 35px; background-color: #e6e9ff; border: 3px solid #000; border-radius: 18px; } .timer_container { width: 75%; margin: 0 auto; } span { font-size: 80px; } .btn { width: 88%; margin: 35px auto; } button { margin: 5px; width: 250px; height: 100px; font-size: 65px; border: 4px solid black; border-radius: 18px; cursor: pointer; } #btnStart { background-color: #FFDE59; } #btnReset { background-color: #FF1616; }
JS
let interval; let timeGap; let click = 0; document.querySelector('#btnReset').addEventListener('click', function () { click = 0; if (interval) clearInterval(interval); displayTime(0, 0, 0, 0); document.querySelector('#btnStart').innerHTML = 'Start' }) document.querySelector("#btnStart").addEventListener('click', function () { if (this.innerHTML === "Start") { this.innerHTML = "Stop"; if (click === 0) { updateTime(0); } else { updateTime(timeGap); } click++; } else if (this.innerHTML === "Stop") { clearInterval(interval) this.innerHTML = "Start"; } }); function updateTime(elapsedTime) { let startTime = Date.now() interval = setInterval(function () { timeGap = Date.now() - startTime + elapsedTime; let hours = parseInt(timeGap / 1000 / 60 / 60); let minutes = parseInt(timeGap / 1000 / 60); let seconds = parseInt(timeGap / 1000); let milliseconds = timeGap; if (seconds >= 60) seconds %= 60; if (minutes >= 60) minutes %= 60; if (milliseconds >= 1000) milliseconds %= 1000; displayTime(hours, minutes, seconds, milliseconds) }, 100) } function displayTime(h, m, s, ms) { document.querySelector("#hour").innerHTML = addZeroes(h, 2); document.querySelector("#minute").innerHTML = addZeroes(m, 2); document.querySelector("#second").innerHTML = addZeroes(s, 2); document.querySelector("#millisecond").innerHTML = addZeroes(ms, 3); } function addZeroes(number, digits) { let myNum = String(number); return new Array(digits - myNum.length + 1).join("0") + myNum; }