这是我使用的初始代码:
setInterval(function(){
r=confirm("You are about to be logged out! Press cancel if you want to remain logged in.");
if (r == true){
window.location.href = '../logout.php';
}else{
location.reload();
}
},30000);
确认对话框等待用户的操作。如果操作是"取消",他们将保持登录状态。如果动作是"ok"它们被重定向到logout.php页面。问题是,如果用户没有响应,他们在30秒后不会注销。
然后我想我可以用两个时间间隔:
setInterval(function(){
window.location.href = '../logout.php';
},60000);
setInterval(function(){
r=confirm("You are about to be logged out! Press cancel if you want to remain logged in.");
if (r == true){
window.location.href = '../logout.php';
}else{
location.reload();
}
},30000);
,但由于confirm()方法停止了脚本,因此60000毫秒从未实现。有什么办法能让它工作吗?
这是我的建议
- 启动定时器,将用户注销
- 启动graceTimer显示链接
- 如果链接被点击,计时器重新启动
- 如果没有,则注销
https://jsfiddle.net/mplungjan/t5ejs72q/
let tId, tId1;
const end = 15000, // change to whatever - 30 minutes
grace = 3000, // 3 secs - should be 30 secs in real life
timer = () => {
clearTimeout(tId);
tId = setTimeout(function() {
// location.replace('../logout.php')
console.log("logged out")
}, end);
},
graceTime = () => tId1 = setTimeout(toggleGrace, end - grace),
toggleGrace = () => document.getElementById("stayLink").classList.toggle("hide"),
init = () => {
timer();
graceTime()
};
document.getElementById("stayLink").addEventListener("click", function(e) {
e.preventDefault();
toggleGrace();
init()
})
init()
.hide {
display: none;
}
<a href="#" id="stayLink" class="hide">Stay logged in?</a>