Prevent onbeforeunload function from pausing javascript timer

我的梦境 提交于 2019-12-10 15:16:22

问题


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?


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/12731865/prevent-onbeforeunload-function-from-pausing-javascript-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!