i tested a simple timer code for showing timer in website. The timer working fine when i am on the page. But when i go the another page or site, after a while when i come back to the timer page i see that timer did not worked correctly in the interval.
Suppose i leave the page for 5 minutes. So when I will come back, I should see 00:05:00. But it is displaying 00:01:00 (around).
But if i dont leave the page it is working fine.
What is the solution?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="time"></h1>
<script>
timerElement = document.getElementById("time");
let seconds = 0, minutes = 0, hours = 0;
timerInterval = setInterval(function () {
seconds++;
if (seconds === 60) {
seconds = 0;
minutes++;
if (minutes === 60) {
minutes = 0;
hours++;
}
}
const formattedTime = `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
timerElement.textContent = formattedTime;
}, 1000);
</script>
</body>
</html>
Even I deployed this on github page. But result is same.