【问题标题】:SetTimeOut speeds Up with multiple tabs openedSetTimeOut 在打开多个标签时加快速度
【发布时间】:2015-08-03 04:55:49
【问题描述】:

我在Layout(MVC4.0) (With 1 Second Interval) 页面上有一个计时器,当网站只有 1 页时它工作正常(在一个标签中 strong>) 已打开

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

【问题讨论】:

  • 如果您使用 sessionStorage 来存储初始时间计数,那么这个问题(从多个选项卡快速递减)将会上升,因为 sessioStorage 对于所有选项卡都是通用的。您可以使用一个简单的 javascript 变量。该变量的范围对于所有选项卡都会有所不同,并且计时器将正常工作。
  • 我已经尝试过你的建议..但我希望计时器在所有选项卡上统一递减(如果打开多个)。因为当计时器归零'0'时,我必须做一些ajax调用......
  • 只存储“倒计时开始”。然后可以根据当前时间计算此后的秒数。这也将确保“一致”(基于 any 选项卡中发生的任何操作),假设要共享倒计时间隔。
  • user2864740 ..我已经编辑了代码..请看一下
  • @user2864740 ..我添加了小提琴链接..请看一下

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


【解决方案1】:

问题是您正在使用正在递减的计数器对所有选项卡都是通用的,因为它保存在 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;
        }

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

【讨论】:

  • 感谢 GPicazo..我的目的是为所有标签共享公共计数器,无论打开多少标签
  • 我添加了小提琴链接..请看一下
  • 我已经分叉了你的小提琴,让我知道它是否有效(链接在答案中)。
猜你喜欢
  • 2010-11-12
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 2020-11-23
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多