Having an issue with my JavaScript stopwatch. When I hit the start button, the stopwatch immediately shows one hour (01:00:00) before counting normally. Any solutions to prevent this instant start at one hour would be highly appreciated. Thank you in advance for a quick response.
<div class="container">
<h1 class="screen">
<span id="hours">
00
</span>:<span id="minutes">
00
</span>:<span id="seconds">
00
</span>
</h1>
<div class="buttons">
<button id="start">START CHARGE</button>
<button id="stop">STOP CHARGE</button>
<button id="reset">RESET TIMER</button>
</div>
</div>
<script>class State {
constructor(startTimestamp, difference, suspended) {
this.startTimestamp = startTimestamp;
this.difference = difference;
this.suspended = suspended;
}
static ready() {
return new State(0, 0, 0);
}
}
class Stopwatch {
constructor(state) {
this.state = state;
this.requestAnimationId = null;
this.handleClickStart = this.handleClickStart.bind(this);
document
.getElementById("start")
.addEventListener("click", this.handleClickStart);
this.handleClickStop = this.handleClickStop.bind(this);
document
.getElementById("stop")
.addEventListener("click", this.handleClickStop);
this.handleClickReset = this.handleClickReset.bind(this);
document
.getElementById("reset")
.addEventListener("click", this.handleClickReset);
this.tick = this.tick.bind(this);
this.render();
}
static ready() {
return new Stopwatch(State.ready());
}
setState(newState) {
this.state = {...this.state,...newState };
this.render();
}
tick() {
this.setState({
difference: new Date(new Date() - this.state.startTimestamp)
});
this.requestAnimationId = requestAnimationFrame(this.tick);
}
handleClickStart() {
if (this.state.startTimestamp) {
return;
}
this.setState({
startTimestamp: new Date() - this.state.suspended,
suspended: 0
});
this.requestAnimationId = requestAnimationFrame(this.tick);
}
handleClickStop() {
cancelAnimationFrame(this.requestAnimationId);
this.setState({
startTimestamp: null,
suspended: this.state.difference
});
}
handleClickReset() {
cancelAnimationFrame(this.requestAnimationId);
this.setState(State.ready());
}
render() {
const { difference } = this.state;
const seconds = (difference ? Math.floor(difference.getSeconds()) : 0)
.toString()
.padStart(2, "0");
const minutes = (difference ? Math.floor(difference.getMinutes()) : 0)
.toString()
.padStart(2, "0");
const hours = (difference ? Math.floor(difference.getHours()) : 0)
.toString()
.padStart(2, "0");
// Render screen
document.getElementById("hours").textContent = hours;
document.getElementById("minutes").textContent = minutes;
document.getElementById("seconds").textContent = seconds;
}
}
const STOPWATCH = Stopwatch.ready()</script>