Francis P
Francis P

Reputation: 13665

Prevent onbeforeunload function from pausing Javascript timer

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?

Upvotes: 4

Views: 1853

Answers (3)

roelandvanbeek
roelandvanbeek

Reputation: 669

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.

Upvotes: 2

Guffa
Guffa

Reputation: 700562

You can't. Javascript is strictly single threaded, so any modal popup will suspend everything else.

Upvotes: 4

manzoid
manzoid

Reputation: 1225

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

Upvotes: 1

Related Questions