简体   繁体   English

能见度变化与预期不符

[英]visibilitychange doesn't behave as intended

The MDN page for visibilitychange states that "it is fired when the content of a tab has become visible or has been hidden". 可见性更改的MDN页指出:“当选项卡的内容变得可见或被隐藏时,它将被触发”。 However, when I run the following snippet, I immediatly get an infinite chain of alerts, so it is apparently being fired constantly. 但是,当我运行以下代码片段时,我立即获得了无限的警报链,因此显然它不断被触发。 Why is this happening? 为什么会这样呢?

 function doEverything() { if(document.visibilityState == 'visible') { alert(document.visibilityState); document.removeEventListener("visibilitychange", doEverything()); } } document.addEventListener("visibilitychange", doEverything()); 

you are calling the function instead of passing it as argument. 您正在调用函数,而不是将其作为参数传递。

document.addEventListener("visibilitychange", doEverything);

and

document.removeEventListener("visibilitychange", doEverything);

Why is this happening? 为什么会这样呢?

The reason is because you are constantly executing the doEverything function in a never-ending loop. 原因是因为您在不断循环中不断执行doEverything函数。

1) doEverything() is first executed here: 1)首先在这里执行doEverything()

document.addEventListener("visibilitychange", doEverything());

2) doEverything() goes into a loop here, constantly displaying the alert : 2) doEverything()在这里进入循环,不断显示alert

function doEverything() {
    if(document.visibilityState == 'visible') {
        alert(document.visibilityState);
        document.removeEventListener("visibilitychange", doEverything());
    }
}

The above can be seen as the equivalent of: 上面的内容可以视为:

function doEverything() {
    if (true) {
        doEverything(); // loop
    }
}

To fix this, you don't want to execute the function but rather provide the reference of the function. 要解决此问题,您不想执行该功能,而是提供该功能的参考。 It's a simple change from doEverything() to doEverything in your addEventListener() and removeEventListener() : 这是在addEventListener()removeEventListener()doEverything()doEverything的简单更改:

function doEverything() {
    if(document.visibilityState == 'visible') {
        console.log('hi');
        document.removeEventListener("visibilitychange", doEverything);
    }
}

document.addEventListener("visibilitychange", doEverything);

This will run the alert only once when the tab is switched. 切换选项卡时,它将仅运行一次警报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM