Stopwatch
This is a small stopwatch app that counts the time. There are three buttons to control it: start, pause and reset. Press Start to start counting time. Press Pause to pause counting. Press Reset to start counting again.In .html file:
<div id="stopwatch-container">
<div id="stopwatch-display">00:00:00</div>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
In .js file:
const display = document.getElementById('stopwatch-display');
const start = document.getElementById('start');
const pause = document.getElementById('pause');
const reset = document.getElementById('reset');
let startTime = 0;
let elapsedTime = 0;
let currentTime = 0;
let paused = true;
let interValId;
let hrs = 0;
let mins = 0;
let secs = 0;
start.addEventListener('click', () => {
if (paused) {
paused = false;
startTime = Date.now() - elapsedTime;
interValId = setInterval(updateTime, 1000);
}
});
pause.addEventListener('click', () => {
if (!paused) {
paused = true;
elapsedTime = Date.now() - startTime;
clearInterval(interValId)
}
});
reset.addEventListener('click', () => {
paused = true;
clearInterval(interValId)
startTime = 0;
elapsedTime = 0;
currentTime = 0;
hrs = 0;
mins = 0;
secs = 0;
display.textContent = "00:00:00"
});
function updateTime() {
elapsedTime = Date.now() - startTime;
secs = Math.floor((elapsedTime / 1000) % 60)
mins = Math.floor((elapsedTime / (1000 * 60)) % 60)
hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 60)
secs = addZero(secs);
mins = addZero(mins);
hrs = addZero(hrs);
display.textContent = `${hrs}:${mins}:${secs}`
function addZero(unit) {
return (("0") + unit).length > 2 ? unit : "0" + unit;
}
};
Comments (0)
Be the first to leave a comment