Search code examples
javascriptsettimeoutdom-eventsonbeforeunload

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?


Solution

  • 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.