I'm trying to create a timer using JavaScript. I have the code below, but the issue is I can't clear the intervals unless I declare them outside, but when I declare them at the beginning, they run without the button click. Any way I can fix that?
let btnTimer = document.querySelectorAll(".timerButton");
let totalTimer = document.getElementById("totalTimer");
let i = 0, j = 0, h = 0, k = 0;
let time = k.toString() + h + ":" + j + i;
totalTimer.innerText = time;
for (item of btnTimer) {
item.addEventListener("click", (e) => {
let btnTmr = e.target.innerText;
if (btnTmr == "Start") {
i = i++;
let intervalI = setInterval(function(){
time = k.toString() + h + ":" + j + i;
totalTimer.innerText = time;
if (i < 9) {
i++;
} else if (i = 9) {
i = 0;
}
}, 1000);
let intervalJ = setInterval(function(){
time = k.toString() + h + ":" + j + i;
totalTimer.innerText = time;
if (j < 6) {
j++;
} else {
j = 0;
}
}, 10000);
} else if (btnTmr == "Pause") {
clearInterval(intervalI);
clearInterval(intervalJ);
} else {
time = "00:00"
totalTimer.innerText = time;
clearInterval(intervalI);
clearInterval(intervalJ);
}
})}