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
Run a function constantly
提问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 isVisible
isn't a global variable and can be accessed by the setInterval
still 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 colorbox
every interval, then logging to the console whether the colorbox
is 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);