I want to achieve the following scenario:
Set a timer of 60 seconds and start the countdown displaying the timer. After the countdown is finished, refresh (not reload) the page and restart the countdown timer and continue the process.
If the browser's tab is changed, after finishing the timer, refresh the page and pause the timer, and only when the tab is active again refresh the page and start the countdown timer again.
I have managed to achieve the first requirement like:
Result will Refresh in <span id="countdown"></span>
<script>
if (!document.hidden) {
function timedRefresh(e) {
var n = setInterval((function () {
e > 0 ? (e -= 1, document.getElementById("countdown").innerHTML = e) : (clearInterval(n), window.location.reload())
}), 1e3)
}
timedRefresh(59)
}
</script>
And is unable to achieve the second requirement. I have tried to implement the solution mentioned here: Is there a way to detect if a browser window is not currently active? But it didn't work.
How do I achieve the requirements in pure JavaScript code?