Is there a way I can make stopwatch but having both timer up and down method?

37 Views Asked by At

`countDown is completed, when i want to start the timer again the timer starts from the vlaue where the countDown was clciked. so, i want a solution that will help me to start the timer from the initial position ie '00:00' Sorry if the question is not understandable as this is my first time asking the question related to coding?


const timeContainer = document.querySelector('.timer--container');
const labelTimer = document.querySelector('#timer');
const start = document.querySelector('#start');
const pause = document.querySelector('#pause');
const reset = document.querySelector('#reset');
const countDown = document.querySelector('#count--down');

let timer = null;
let time = parseInt(labelTimer.textContent);

const tick = function () {
const min = String(Math.trunc(time / 60)).padStart(2, 0);
const sec = String(time % 60).padStart(2, 0);
time++;
labelTimer.textContent = `${min}:${sec}`;
console.log(labelTimer.textContent);
};

start.addEventListener('click', function () {
tick();
if (timer !== null) {
clearInterval(timer);
}
timer = setInterval(tick, 1000);
});

pause.addEventListener('click', function () {
clearInterval(timer);
});

reset.addEventListener('click', function () {
if (timer !== null) clearInterval(timer);
time = parseInt(labelTimer.textContent);
console.log(time);
labelTimer.textContent = `00:00`;
});

countDown.addEventListener('click', function () {
if (labelTimer.textContent !== '00:00') {
const \[min, sec\] = labelTimer.textContent.split(':');
let time = parseInt(min) \* 60 + parseFloat(sec);
function tick() {
const min = String(Math.trunc(time / 60)).padStart(2, 0);
const sec = String(time % 60).padStart(2, 0);
labelTimer.textContent = `${min}:${sec}`;
console.log(labelTimer.textContent);
time--;
if (time < 0) {
clearInterval(timer);
timer = null;
}
}
tick();
timer = setInterval(tick, 1000);
}
});


`


start.addEventListener('click', function () {
if (labelTimer.textContent === '00:00') {
tick();
if (timer !== null) {
clearInterval(timer);
ie;
}
timer = setInterval(tick, 1000);
}
});

` tried this so that it will start from the initial position but this also resulted in same output

eg.i click start btn and coutup to 5sec, then i paused it and clicked the countDown btn where the textContent goes to '00:00', when I try to click start button it starts counting up again from the 5sec`

0

There are 0 best solutions below