SetTimeOut在打开多个选项卡时加速

时间:2015-08-03 04:55:49

标签: javascript jquery asp.net-mvc jquery-ui

我在Layout(MVC4.0)( 1秒间隔)页面上有一个计时器自动收报机,当只有1页网站时,它可以正常工作(在一个标签中)已打开

var timeOutMinutes = 10;
var timeOutSeconds = timeOutMinutes * 60;
localStorage.setItem("SessionCounter", timeOutSeconds);

var popUpShown = false;
var logOutCalled = false;

$(document).ready(function () {
  setInterval(TimerDecrement, 1000);
});

function TimerDecrement() {
    if (timeOutSeconds > 0) {
        if (parseInt(localStorage.getItem("SessionCounter"), 10) > 0) {
            timeOutSeconds = parseInt(localStorage.getItem("SessionCounter"), 10);
        }
        timeOutSeconds--;
        localStorage.setItem("SessionCounter", timeOutSeconds);
    }
    else {

        if (!logOutCalled) {
            logOutCalled = true;
            LogOut();
        }
        else {
            logOutCalled = true;
        }
    }

    document.getElementById("seconds").innerHTML = timeOutSeconds;
    document.getElementById("secondsIdle").innerHTML = timeOutSeconds;

    if (timeOutSeconds < 500) {
        //alert(history.length);
        popUpShown = true;
        $("#pnlPopup").dialog("open");
    }
    else {
        if ($("#pnlPopup").dialog("isOpen")) {
            popUpShown = false;
            $("#pnlPopup").dialog("close");
        }
    }
}

但是,当我打开多个标签的网站计时器时,跳跃会迅速减少。

即使在多个标签中打开网站,如何保持计时器统一减少?

FIDDLE

1 个答案:

答案 0 :(得分:1)

问题是您正在使用正在递减的计数器对所有选项卡都是通用的,因为它保存在LocalStorage中。因此,解决方案实际上取决于您对减量计数器的意图。

如果每个会话(每个标签)的目的是让它拥有独立的计数器,那么使用变量而不是LocalStorage可以更好地服务 - 或者,为每个计数器使用唯一的会话ID在LocalStorage中。

如果打算让所有标签共享相同的减量计数器,但是不管打开多少个标签,它每秒只减少一次,那么也许你想要存储计数器以及最后的减量时间

编辑:这是一个分叉的小提琴,可能会做你需要的:

http://jsfiddle.net/y68m4zwr/8/

它的要点是添加:

var lastUpdated = localStorage.getItem("SessionCounterUpdatedOn"),
            now = new Date(), shouldCheck = false;

        if (lastUpdated == null) {
            localStorage.setItem("SessionCounterUpdatedOn", now);
        } else if (now.getTime() - new Date(lastUpdated).getTime() >= 1000) {
            // set this immediatedly so another tab checking while we are processing doesn't also process.
            localStorage.setItem("SessionCounterUpdatedOn", now);
            shouldCheck = true;
        }

检查计数器的最后更新记录,如果在第二次更新前更新,它只更新剩余时间,否则执行逻辑递减。