我正在尝试为登录我的页面的用户设置超时。我有一个从别处复制的工作超时函数,但我担心一个小问题。有问题的页面是单个页面,它通过 jQuery/PHP 重新加载其内容,而不是将用户导航到不同的 URL。
事件侦听器检查任何用户活动,并在发生这种情况时重置超时。我希望计时器仅在用户登录时运行,一旦超时达到零,它将用户注销。idleEnabled
当人们登录/注销/超时时,我通过在 true 和 false 之间切换全局变量来实现这一点。
我的问题:虽然超时功能仅在用户登录的情况下在事件侦听器中可用,但事件侦听器本身被永久激活并通过简单地移动鼠标不断地 ping。我担心这可能会占用客户端浏览器的容量。
我所拥有的:我一直在寻找是否可以将事件侦听器放入其中,if (idleEnabled == true) { listener here }
但据我所知这是不可能的。即使是这样,我也很确定只有在加载脚本时才会运行平面 if 语句,但是当页面本身没有重新加载时,相关变量会发生变化。
主要问题:有没有办法做到这一点?或者这很好,我是否担心一些无关紧要的事情?
附带问题:我读到使用 javascript 全局变量并不可取,但我不知道任何其他方法可以做到这一点。像这样使用它们可以吗?
相关的jQuery代码:
//create a global timeout handle
var idleTimer = null;
var idleEnabled = false;
var idleWait = 10000; //This is low for testing purposes
//to prevent the timer from disappearing if people refresh the page,
//check if the logout button is on the page when loading the script:
if ($("#logout").length) {window.idleState = true;}
$('*').on('mousemove keydown scroll', function () { //listen for activity
if (idleEnabled == true) { //if the timer is enabled...
clearTimeout(window.idleTimer); //...clear it,
window.idleTimer = setTimeout(function () { //and reset it, so that...
$(document).trigger("timeOut"); //...the custom timeout event fires
window.idleEnabled = false; //...and the timer is disabled
}, idleWait);
}
});
$(".column").on("click", "#login, #logout", {cause: "user"}, validateUser) //Call a validation on login/logout
$(document).on("timeOut", {cause: "timeout"}, validateUser) //Call a validation on timeout
//The function validateUser will set idleEnabled = true on login and idleEnabled = false on logout.
您绝对应该能够在if
分支内添加侦听器。登录时,您需要重新设置。这是我将如何做到的:
var idleTimer = null;
var idleWait = 10000;
// There is probably a better way to check if the user is logged in
function isLoggedIn() {
return $("#logout").length > 0;
}
function setActivityListener(active) {
if (active)
$('*').on('mousemove keydown scroll', activityHandler);
else
$('*').off('mousemove keydown scroll');
}
function activityHandler() {
clearTimeout(idleTimer);
idleTimer = setTimeout(function () {
$(document).trigger("timeOut");
}, idleWait);
};
if (isLoggedIn()) {
setActivityListener(true);
}
$(".column").on("click", "#login, #logout", {cause: "user"}, validateUser);
$(document).on("timeOut", {cause: "timeout"}, validateUser);
// On login (in validateUser?)
setActivityListener(true);
// On logout
setActivityListener(false);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句