StopwatchMiniProject
This commit is contained in:
41
MiniProjects/StopWatch/watch.js
Normal file
41
MiniProjects/StopWatch/watch.js
Normal file
@ -0,0 +1,41 @@
|
||||
//The stopwatch is incremented using a closure function!
|
||||
function stopwatch() {
|
||||
var time = new Date(0, 0, 0, 0, 0, 0, 0);
|
||||
var pause = false;
|
||||
|
||||
function increment() {
|
||||
if (!pause) {
|
||||
time.setSeconds(time.getSeconds() + 1);
|
||||
const hours = time.getHours().toString().padStart(2, "0");
|
||||
const minutes = time.getUTCMinutes().toString().padStart(2, "0");
|
||||
const seconds = time.getUTCSeconds().toString().padStart(2, "0");
|
||||
document.getElementById("time").innerHTML = `${hours}:${minutes}:${seconds}`;
|
||||
}
|
||||
}
|
||||
|
||||
function pauseTimer() {
|
||||
pause = true;
|
||||
}
|
||||
|
||||
return { increment, pauseTimer };
|
||||
}
|
||||
|
||||
var timer = stopwatch();
|
||||
var intervalId;
|
||||
|
||||
function start() {
|
||||
if (!intervalId) {
|
||||
intervalId = setInterval(timer.increment, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
timer.pauseTimer();
|
||||
}
|
||||
|
||||
function reset() {
|
||||
clearInterval(intervalId);
|
||||
intervalId = null;
|
||||
timer = stopwatch();
|
||||
document.getElementById("time").innerHTML = "00:00:00";
|
||||
}
|
Reference in New Issue
Block a user