我在布局
(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 中。因此,解决方案实际上取决于您对减量计数器的意图。
如果目的是让每个 session (每个选项卡)拥有自己单独的计数器,那么使用变量而不是 LocalStorage 会更好,或者为 LocalStorage 中的每个计数器使用唯一的 session ID。
如果目的是让所有选项卡共享相同的递减计数器,但无论打开多少个选项卡,它每秒仅递减一次,那么您可能想要存储计数器以及最后一次递减时间.
编辑:这是一个 fork 的 fiddle ,可以满足您的需要:
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;
}
它检查计数器的最后更新记录,如果在不到一秒前更新,它只会更新剩余时间,否则执行递减逻辑。
关于javascript - SetTimeOut 加快打开多个选项卡的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31779648/