I can’t understand. Wrote code for 2 independent timers. But when you press the start button, both timers start. What am I doing wrong, tell me?
I tried with conditions, but it didn’t work. Maybe we can somehow solve this? I don’t have any ideas anymore.
Here is the code:
const res = document.getElementById('res'),
btnStart = document.getElementById('start'),
btnStop = document.getElementById('stop');
const res1 = document.getElementById('res1'),
btnStart1 = document.getElementById('start1'),
btnStop1 = document.getElementById('stop1');
function getCounter(el, startBtn, stopBtn) {
let sec = 0;
let min = 0;
let hours = 0;
let interval;
let isAvtive = false;
function updateCounter() {
sec++;
if (sec === 60) {
min++;
sec = 0;
}
if (min === 60) {
hours++;
min = 0;
}
if (hours === 24) {
hours = 0;
}
el.textContent = sec;
if (btnStart) {
res.textContent = `${hours.toString().padStart(2,0)}:${min.toString().padStart(2,0)}:${sec.toString().padStart(2,0)}`;
}
if (btnStart1) {
res1.textContent = `${hours.toString().padStart(2,0)}:${min.toString().padStart(2,0)}:${sec.toString().padStart(2,0)}`;
}
}
startBtn.addEventListener('click', function() {
if (btnStart)
interval = setInterval(updateCounter, 1000);
});
stopBtn.addEventListener("click", function() {
if (interval) {
clearInterval(interval)
interval = null;
}
})
}
getCounter(res, btnStart, btnStop);
getCounter(res1, btnStart1, btnStop1);
<input type="button" value="start" id="start" />
<input type="button" value="stop" id="stop" />
<span id="res"></span>
<br/>
<input type="button" value="start1" id="start1" />
<input type="button" value="stop1" id="stop1" />
<span id="res1"></span>
2
Answers
Inside the updateCounter function, the isActive flag is used to determine whether the timer has started. The timer is only started if isActive is false. This allows each timer to be controlled independently of the other.
Make a function to create a timer in a parent element, you can provide a HTML template and insert it instead of repeating it in HTML.
Don’t use
setInterval/setTimeout
since they aren’t precise and throttled in inactive tabs. Just calculate difference between start and current time. For smooth display userequestAnimationFrame()
so your display would be also precise: