如果您想在 X 时间后关闭会话,无论是否发出 ajax 请求,但前提是用户在页面上没有活动,您可以使用我正在使用的以下代码:
(function () {
// After 30 minutes without moving the mouse, the user will be redirect to logout page
var time2refresh = 30;
// This is how many time the user has to be inactive to trigger the countdown of 30 minutes
var timeInactive = .5;
// This will store the timer in order to reset if the user starts to have activity in the page
var timer = null;
// This will store the timer to count the time the user has been inactive before trigger the other timer
var timerInactive = null;
// We start the first timer.
setTimer();
// Using jQuery mousemove method
$(document).mousemove(function () {
// When the user moves his mouse, then we stop both timers
clearTimeout(timer);
clearTimeout(timerInactive);
// And start again the timer that will trigger later the redirect to logout
timerInactive = setTimeout(function () {
setTimer();
}, timeInactive * 60 * 1000);
});
// This is the second timer, the one that will redirect the user if it has been inactive for 30 minutes
function setTimer() {
timer = setTimeout(function () {
window.location = "/url/to/logout.php";
}, time2refresh * 60 * 1000);
}
})();
所以这个函数的逻辑是这样的:
1) 用户登录到您的站点 2) 在 0.5 分钟(30 秒)不活动后,将开始一个 30 分钟的倒计时 3) 如果用户移动鼠标,两个计时器都会重置,第一个计时器会重新开始。4) 如果 30 分钟后用户没有移动他的鼠标,那么它将被重定向到注销页面,关闭他的会话。