Prevent onbeforeunload function from pausing javas

2019-06-25 13:12发布

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?

3条回答
Animai°情兽
2楼-- · 2019-06-25 13:23

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

查看更多
神经病院院长
3楼-- · 2019-06-25 13:42

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

查看更多
Melony?
4楼-- · 2019-06-25 13:48

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.

查看更多
登录 后发表回答