Problem
I have a simple timer which should be paused or reset by clicking a button. My problem is that the interval keeps running. Basically I save the identifier in the time
variable and try to reset it when a pause or stop button is clicked. The variable should be publicly accessible, so I don't know where it goes wrong.
Code
Here is the (shortened) code in question:
let total = 0;
let minutes = 0;
let seconds = 0;
let hours = 0;
let running = false;
let time;
$: normalizedHours = hours > 9 ? hours : `0${hours}`;
$: normalizedMinutes = minutes > 9 ? minutes : `0${minutes}`;
$: normalizedSeconds = seconds > 9 ? seconds : `0${seconds}`;
$: title = `${normalizedHours}:${normalizedMinutes}:${normalizedSeconds}`;
function run() {
if (running) {
return;
}
running = true;
timer();
}
function timer() {
time = setInterval(() => {
total++;
if (seconds == 59) {
seconds = 0;
if (minutes == 9) {
minutes++;
} else if (minutes == 59) {
minutes = 0;
if (hours == 23) {
hours = 0;
}
hours++;
} else {
minutes++;
}
} else {
seconds++;
}
}, 1000);
}
function pause() {
clearInterval(time);
time = null;
running = false;
}
function reset() {
pause();
hours = 0;
minutes = 0;
seconds = 0;
}
const buttons = [
{ title: "Play", click: run, icon: "play" },
{ title: "Pause", click: pause, icon: "pause" },
{ title: "Reset", click: reset, icon: "stop" },
];
</script>
<section>
<form on:submit|preventDefault={run}>
<div class="controls">
{#each buttons as { title, click, icon }}
<button {title} on:click={click}>
<i class={`fa fa-${icon}-circle`} />
</button>
{/each}
</div>
<div class="time">{normalizedHours}</div>
<span>:</span>
<div class="time">{normalizedMinutes}</div>
<span>:</span>
<div class="time">{normalizedSeconds}</div>
</form>
</section>
Repl
Here is a link to the repl where you can see / debug the problem.