【问题标题】:javascript autologout for inactivity for 10 minutesjavascript自动注销10分钟不活动
【发布时间】:2015-12-23 09:20:44
【问题描述】:

你好,我正在编写一个代码用于自动注销大约 20 分钟的不活动状态,它应该与键盘和鼠标交互,我有以下代码,它适用于大多数功能,但它不会重置鼠标移动的计时器和键盘活动。

var timoutWarning = 9000; // Display warning in 14 Mins.
var timoutNow = 9000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = 'logout.php'; // URL to logout page.

var warningTimer;
var timeoutTimer;

// Start warning timer.
function StartWarningTimer() {
    warningTimer = setTimeout("IdleWarning()", timoutWarning);
}

// Reset timers.
function ResetTimeOutTimer() {
    clearTimeout(timeoutTimer);
    StartWarningTimer();
    $("#timeout").hide();
}

// Show idle timeout warning dialog.
function IdleWarning() {
    clearTimeout(warningTimer);
    timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    $("#timeout").show();
}

// Logout the user.
function IdleTimeout() {
    window.location = logoutUrl;
}
$( document ).ready(function() {
    StartWarningTimer();
});
$('html').mousemove(function() {
    ResetTimeOutTimer();
});

我希望代码应该通过鼠标移动和键盘按下来吸引 感谢您提供各种帮助,请给我一些建议

【问题讨论】:

标签: javascript timer


【解决方案1】:

首先,您不应该以这种方式使用setTimeout - 非活动标签getting slower,因此无法保证您的代码将在 14 分钟内执行。更好的方法是反复检查经过的时间。

var startTime = +new Date();
function checkForWarning () {
    if (+new Date() - startTime > maxInactiveTime) {
        // show warning
    }
}

您可以通过这种方式跟踪活动:

$(document)
    .on('click', ResetTimeOutTimer)
    .on('mousemove', ResetTimeOutTimer);

希望对你有帮助。

【讨论】:

  • 您必须通过当前时间与您开始计数的时刻之间的差异来计算经过的时间。这是可靠的方法。这就是我的代码所做的——我们记得我们在 startTime 中开始的那一刻。然后是检查时间是否到了的方法(checkForWarning)。我们应该重复调用它,像这样 setTimeout(checkForWarning, 1000 * 60)
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 2016-04-13
  • 2018-06-21
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 2020-09-11
相关资源
最近更新 更多