javascript 不断地运行一个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16447996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:42:02  来源:igfitidea点击:

Run a function constantly

javascriptjqueryviewportinview

提问by eozzy

I'm using the excellent inViewplugin to check if an element is visible in the viewport, using setInterval, but the function only runs once and only when the element IS visible, not otherwise (should run else statement).

我正在使用优秀的inView插件来检查元素是否在视口中可见,使用 setInterval,但该函数仅运行一次且仅在元素可见时运行,否则(应运行 else 语句)。

var checkViewport = setInterval(function() {
    $('#colorbox').on('inview', function(event, visible) {
      if (visible) {
        console.log('YES');
      } else {
        console.log('NO');
      }
    });
}, 5000);

回答by Ian

Bind the event once, and check a separate variable. Try this:

绑定事件一次,并检查一个单独的变量。试试这个:

var isVisible = false;

$('#colorbox').on('inview', function(event, visible) {
    isVisible = visible;
});

var checkViewport = setInterval(function() {
    if (isVisible) {
        console.log('YES');
    } else {
        console.log('NO');
    }
}, 5000);

You can structure this differently to make sure isVisibleisn't a global variable and can be accessed by the setIntervalstill as well.

您可以以不同的方式构造它以确保isVisible它不是全局变量并且也可以被setInterval静止访问。

回答by KernelPanik

The code in your example only binds an event when the element's in the viewport. You're not actually executing anything, just repeatedly binding an event.

您示例中的代码仅在元素位于视口中时绑定事件。您实际上并没有执行任何操作,只是重复绑定一个事件。

I would suggest instead checking the element colorboxevery interval, then logging to the console whether the colorboxis visible.

我建议改为colorbox每隔一段时间检查元素,然后记录到控制台是否colorbox可见。

Source (HTML DOM and JavaScript):

源代码(HTML DOM 和 JavaScript):

var checkViewport = setInterval(function() {
    myColorBox = document.getElementById("colorbox");
      if (myColorBox.style.visibility == "visible") {
        console.log('YES');
      } else {
        console.log('NO');
      }
    });
}, 5000);