gpt4 book ai didi

javascript - 在另一个选项卡中设置 ClearTimeout

转载 作者:行者123 更新时间:2023-12-03 07:21:35 26 4
gpt4 key购买 nike

如何清除浏览器中另一个选项卡中设置的超时

我尝试在 localStorage 中存储超时引用,但无法清除timeout

function setIdleTimeout() {
var idleTimeout = setTimeout(function() {
//autologout
}, 20000);
localStorage.setItem('idleTimeout', idleTimeout);
}

function clearIdleTimeout() {
var idleTimeout = localStorage.getItem('idleTimeout');
clearTimeout(idleTimeout);
localStorage.setItem('idleTimeout', idleTimeout);
}

如果我在第二个选项卡中调用clearIdleTimeout(),它不会清除前一个选项卡中设置的timeout

最佳答案

选项卡“a”

var timeout, interval;

timeout = setTimeout(function() {
alert(123) // this should not be called
clearTimeout(timeout)
timeout = null;
clearInterval(interval);
interval = null;
}, 20000);
localStorage.setItem("timeout", timeout);

interval = setInterval(function() {
console.log("checking localStorage:", localStorage.getItem("timeout"));
// if `!localStorage.getItem("timeout")` : `true`
// call `clearTimeout()` with `timeout` as paramter
if (!localStorage.getItem("timeout")) {
clearTimeout(timeout);
timeout = null;
alert("cleared");
clearInterval(interval);
interval = null;
}
}, 100)

plnkr http://plnkr.co/edit/wttPFS5RLgCu5OnF05Z1?p=info

标签“b”

var t;
t = setTimeout(clearTabTimeout, 5000);

// clear `timeout` at `tab` "a"
function clearTabTimeout() {
// remove `"timeout"` item from `localStorage`
localStorage.removeItem("timeout");
console.log(localStorage);
}

plnkr http://plnkr.co/edit/CgQqlVIUzUo7zeHCb2Ca?p=preview

关于javascript - 在另一个选项卡中设置 ClearTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36190731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com