为什么页面重新加载使设置的超时失效以及如何避免它?

时间:2016-05-10 15:31:00

标签: javascript html settimeout reload

我有一个网站,我可以使用Javascript自动导航循环来模仿用户的操作。

对于出现问题并且循环停止工作的情况,我有一个故障保护机制。在每次迭代时,执行以下代码:

var failsafe = function () {
    console.log("Something went wrong, reloading...");

    window.location.reload();
    document.failsafeTimeout = setTimeout(failsafe, 60000);
};

if (document.failsafeTimeout !== undefined) {
    // the previous iteration went fine, clearing the old timeout

    clearTimeout(document.failsafeTimeout);
}

document.failsafeTimeout = setTimeout(failsafe, 60000);

问题是,代码没有像我期望的那样工作。当循环中断时,故障安全处理程序被调用一次,但是,尽管再次设置,但永远不会再次调用。故障安全处理程序完成执行后,document.failsafeTimeoutundefined。我假设window.location.reload()异步工作,在failsafeTimeout属性被分配后会破坏它。

如何重写故障安全超时处理程序,以便它可以设置一个新的超时,该超时将在页面重新加载后继续存在?

1 个答案:

答案 0 :(得分:1)

window.location.reload()完全重新加载页面,这会破坏任何javascript调用。

您仍然可以通过监听onunload事件来运行一些代码,但不要期望代码在会话之间保持不变(或者您必须事先在cookie或localStorage中序列化数据)