javascript以检查元素是否可见并设置"setInterval"因此 [英] javascript to check if element visible and set "setInterval" accordingly
问题描述
LE2.还有其他解决方法吗?
我有这段代码,无法弄清楚为什么不能正常工作:
I have this code and can't figure why is not working properly:
$(function autorun() {
if ($("#contactForm").is(":visible")){
setInterval( "refreshAjax();", 150000000000 );
}
else {
setInterval( "refreshAjax();", 15000 );
}
setTimeout("autorun();", 2000)
});
...
<body onLoad="autorun()">
现在,即使"contactForm"可见,它也会每2秒刷新一次页面.
Right now it keep refreshing the page every 2 secs, even if the "contactForm" is visible.
我的逻辑是:如果"contactForm"可见,则延迟刷新或停止它,继续检查,但与此同时,根据另一条语句刷新页面.
My logic is: if the "contactForm" is visible, delay the refresh or stop it, keep checking that, but in the mean time refresh the page accordingly to the other statement.
LE.
$(function() {
refreshAjax = function(){$("#flex1").flexReload();
}
});
LE2. @Nick Craver
LE2. Final solution provided here by @Nick Craver
$(function () {
var ajaxTimeout;
function autorun() {
if ($("#contactForm").is(":visible")){
if(ajaxTimeout) {
clearInterval(ajaxTimeout);
ajaxTimeout = false;
}
}
else if(!ajaxTimeout) {
ajaxTimeout = setInterval(refreshAjax, 15000);
}
}
setInterval(autorun, 2000);
});
谢谢, 克里斯蒂安.
推荐答案
当前,您正在创建很多间隔计时器,这不好.我不知道这是否可以解决您的问题,因为除此之外,您的代码看起来还可以.
Currently you are creating a lot of interval timers which is not good. I don't know if this fixes your problem, because apart from that, your code looks ok.
尝试一下:
var ajaxTimeout;
function autorun() {
if ($("#contactForm").is(":visible")){
if(ajaxTimeout) {
clearInterval(ajaxTimeout);
ajaxTimeout = false;
}
}
else if(!ajaxTimeout) {
ajaxTimeout = setInterval(refreshAjax, 15000);
}
}
$(function() {
setInterval(autorun, 2000)
});
请记住时间以毫秒为单位.
Remember that the time is in milliseconds.
更新:@tec还有另一个有趣的解决方案.因此,这取决于您实际上要用代码实现什么.
Update: @tec has another interesting solution. So it depends on what you actually want to achieve with your code.
这篇关于javascript以检查元素是否可见并设置"setInterval"因此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!