I’m working on a simple time tracker project and I’ve written the following JavaScript code. The goal is to track the elapsed time, with options to start and stop the timer.
let startTime;
let elapsedTime = 0;
let timerInterval;
function startTimer() {
startTime = Date.now() - elapsedTime;
timerInterval = setInterval(() => {
elapsedTime = Date.now() - startTime;
document.getElementById('elapsed-time').textContent = (elapsedTime / 1000).toFixed(1);
}, 100);
}
function stopTimer() {
clearInterval(timerInterval);
}
document.getElementById('start-button').addEventListener('click', startTimer);
document.getElementById('stop-button').addEventListener('click', stopTimer);
<div>
<h1>Simple Time Tracker</h1>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<p>Elapsed Time: <span id="elapsed-time">0</span> seconds</p>
</div>
I’ve been using Traqq as an example for my project. However, I’m running into an issue where the timer doesn’t reset correctly when stopping and then starting again. I always get the cumulative time instead of it resetting back to zero.
Does anyone have an idea on how to correctly reset the timer so it starts from zero each time? Any suggestions or improvements on my current approach would be greatly appreciated.
I added an additional button to reset the timer and tried to reset elapsedTime
to 0
when the stopTimer
function is called. However, that didn’t work as expected. Specifically, I added:
<button id="reset-button">Reset</button>