下面的代码在用户进入页面30秒后发送30s
事件do Google Analytics。
setTimeout(function(){
gtag('event', '30s');
}, 30000);
但是,当用户最小化窗口时,事件仍然会触发。
我真正想要的是一种";暂停";当用户最小化页面时的setTimeout
,并且当他最大化页面时,setTimeout
从其停止的那一刻起继续计数。
我试图将setTimeout
放在hasFocus
语句中,但它没有按预期工作。
有什么办法吗?
您可以使用页面可见性API来检测页面焦点何时丢失。隐藏时,清除现有超时,并将剩余时间设置为变量;如图所示,设置具有剩余时间的setTimeout
。大致如下:
let run = false;
const fn = () => {
gtag('event', '30s');
run = true;
};
let timeoutId;
let runAt;
let timeLeft = 30_000;
const resume = () => {
runAt = Date.now() + timeLeft;
timeoutId = setTimeout(fn, timeLeft);
};
resume();
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
timeLeft = runAt - timeLeft;
clearTimeout(timeoutId);
} else if (!run) {
resume();
}
});
您可以使用document.hidden:
setInterval(() => console.log(document.hidden), 1000)