SetTimeOut加速多个选项卡打开

SetTimeOut speeds Up with multiple tabs opened

本文关键字:选项 加速 SetTimeOut      更新时间:2023-09-26

我在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");
        }
    }
}

但是当我打开多个选项卡时,的网站计时器会迅速下降。

如果在中打开多个选项卡,我如何保持计时器均匀递减?

小提琴

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

如果目的是让每个会话(每个选项卡)都有自己独立的计数器,那么您最好使用变量而不是LocalStorage——或者,为LocalStorage中的每个计数器使用唯一的会话id。

如果目的是让所有选项卡共享相同的递减计数器,但无论打开了多少选项卡,每秒只递减一次,那么可能需要存储计数器以及最后一次递减时间。

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

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;
        }

检查计数器的最后更新记录,如果更新时间少于一秒,则只更新剩余时间,否则执行逻辑减量