In my webpage, I have a countdown timer using javascript's setTimeout()
.
function Tick() {
if (RemainingSeconds <= 0) {
alert("Time is up.");
return;
}
RemainingSeconds -= 1;
ElapsedSeconds += 1;
UpdateTimerDisplay();
window.setTimeout("Tick()", 1000);
}
I also have a function triggered on onbeforeunload
to "prevent" the user from leaving the page.
window.onbeforeunload = function () {
if (!isIEAjaxRequest) {
return "You should use the logout button to leave this page!";
}
else {
isIEAjaxRequest = false;
}
};
The problem is that when the "Are you sure you want to leave this page?" window prompts, it pauses the setTimeout()
function. Any thoughts on how to prevent this?
No, you can't keep updating the UI in the background while the UI thread is consumed with another task (in this case, presenting that native modal dialog prompt).
See Javascript timeout - specification
You can't. Javascript is strictly single threaded, so any modal popup will suspend everything else.
A possible workaround would maybe be to use
var before = new Date()
to store the time before your dialog appears and then use that one to calculate the passed time after your dialog disappears to make up for the missed seconds.