gpt4 book ai didi

javascript - Chrome 标签卡住和 SetTimeout/Web Workers

转载 作者:行者123 更新时间:2023-12-04 10:41:49 24 4
gpt4 key购买 nike

Chrome 79 刚刚发布,带有 new tab freezing feature默认开启。有没有人知道在 JavaScript 中使用 setTimeouts(甚至网络 worker )时解决这个问题的方法?

我们运行了一些代码来检查客户端事件,以便在一段时间后更优雅地超时/注销。不幸的是,当标签处于“冷冻”状态时,这些工作都不是。

有任何想法吗?

最佳答案

基于 age lifecycle api我创建了这个类:

const pageLifecycle = new class PageLifecycle extends EventTarget {
constructor() {
super();
this.state = this.getState();
const fn = () => this.stateChange(this.getState()),
opt = { capture: true },
events = {
pageshow: fn,
focus: fn,
blur: fn,
visibilitychange: fn,
resume: fn,
freeze: () => this.stateChange("frozen"),
pagehide: event => this.stateChange(event.persisted ? "frozen" : "terminated")
};
for (const [event, fn] of Object.entries(events)) window.addEventListener(event, fn, opt);
}
getState() {
return document.visibilityState === "hidden" ? "hidden" : document.hasFocus() ? "active" : "passive";
}
stateChange(nextState) {
if (nextState === this.state) return;
const prevState = this.state;
this.state = nextState;
this.dispatchEvent(Object.assign(new Event("stateChange"), { prevState, state: this.state }));
}
};

//--------
pageLifecycle.addEventListener("stateChange", event => console.log(`State change: ${event.prevState} >>> ${event.state}`));


你可以给它添加一个事件监听器(事件: stateChange),你会得到其中之一 ["active", "passive", "hidden", "frozen", "terminated"]event.state .检查 passive并保存您的数据。您可以查看 event.prevState获取先前的状态以确定是否应该强制检查后端以查看用户是否仍在登录。

关于javascript - Chrome 标签卡住和 SetTimeout/Web Workers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59901862/

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