PDA

View Full Version : Make countdown reset when a new tab or window is opened



perky416
Aug 2nd, 2017, 02:07 PM
Hi guys,

I have the following script that displays a countdown timer in my header, this time is set to coincide with the lifetime of my php session.
The problem I am having is that when multiple tabs or windows are open the countdown times are different. Is there a way to get the timers to all sync with each other? For example when a new tab is opened the timer on all current tabs resets, or when the page on the new tab is refreshed all other instances of the timer refresh?

Many Thanks



<script>
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);

// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;

minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = minutes + ":" + seconds;

if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
window.location.reload()
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}

window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>

jmrker
Aug 2nd, 2017, 04:10 PM
Have you considered using a local storage session variable?

See: https://www.w3schools.com/html/html5_webstorage.asp
Or: HTML5 Local Storage and Session Storage (http://mrbool.com/html5-local-storage-and-session-storage/26282)