防止暂停Javascript计时器时onbeforeunload函数

问题描述 投票:4回答:3

在我的网页中,我有一个使用Javascript的setTimeout()的倒数计时器。

    function Tick() {
        if (RemainingSeconds <= 0) {
            alert("Time is up.");
            return;
        }
        RemainingSeconds -= 1;
        ElapsedSeconds += 1;
        UpdateTimerDisplay();
        window.setTimeout("Tick()", 1000);
    }

[我还在onbeforeunload上触发了一个功能,以“防止”用户离开页面。

    window.onbeforeunload = function () {
        if (!isIEAjaxRequest) {
            return "You should use the logout button to leave this page!";
        }
        else {
            isIEAjaxRequest = false;
        }
    };

问题是,当“您确定要离开此页面吗?”窗口提示时,它将暂停setTimeout()功能。对如何防止这种情况有任何想法?

javascript settimeout dom-events onbeforeunload
3个回答
2
投票

一种可能的解决方法可能是使用var before = new Date()存储对话框出现之前的时间,然后使用该值来计算对话框消失之后的经过时间,以弥补错过的秒数。


4
投票

你不能。 JavaScript严格来说是单线程的,因此任何模式弹出窗口都将挂起其他所有内容。


1
投票

否,当UI线程被另一个任务占用时(在这种情况下,将显示本机模态对话框提示),您将无法在后台继续更新UI。

请参见Javascript timeout - specification

© www.soinside.com 2019 - 2024. All rights reserved.