In my web page, 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?
In my web page, 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?
-
3
Unrelated to the question, you should write the code as
window.setTimeout(Tick, 1000);
. Putting the function name in a string just makes the engine parse the JavaScript. – Heretic Monkey Commented Oct 4, 2012 at 16:47 - I've been thinking of an approach where your beforeunload handler triggers an event and then returns false, so the unload is cancelled. The handler for the event then pops up a dialog asking if you want to leave, and unloads if you say yes. The thing I'm not sure of is whether you can find out what the user wanted to do when the unload was originally triggered (close the window, navigate to another page, etc.). IWBNI the handler received a parameter with this info. – Barmar Commented Oct 4, 2012 at 18:02
- No Barmar, that's not possible for security reasons. If you could prevent the user from closing a web page, you can be sure all those annoying pop-ups would use that! ;) – Francis P Commented Oct 4, 2012 at 18:27
3 Answers
Reset to default 4You 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.
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