【发布时间】:2020-05-05 14:26:01
【问题描述】:
我正在尝试为在我的页面上登录的用户设置超时。我有一个从其他地方复制的工作超时功能,但有一个我担心的小问题。有问题的页面是一个单独的页面,它通过 jQuery/PHP 重新加载其内容,而不是将用户导航到不同的 URL。
事件侦听器检查任何用户活动,并在发生这种情况时重置超时。我希望计时器仅在用户登录时运行,一旦超时达到零,它就会将用户注销。我通过在人们登录/注销/超时时在 true 和 false 之间切换全局变量 idleEnabled 来实现这一点。
我的问题:超时功能仅在用户登录时才在事件监听器中可用,而事件监听器本身是只需移动鼠标即可永久激活并不断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.
【问题讨论】:
标签: jquery if-statement settimeout event-listener