clearInterval不会clearInterval [英] clearInterval doesn't clearInterval
问题描述
var定时器;函数check_element_load(){计时器= window.setInterval(function(){console.log(仍在工作");//永远运行if(document.getElementById("comments")){console.log("FOUND");//这实际上运行document.getElementsByTagName("fb:comments")[0] .setAttribute('order_by','social');window.clearInterval(timer);//<没有效果}},50);}check_element_load();
我正在尝试在脚本上方放置一个脚本,以检查特定元素是否已成功加载到浏览器中,它可以正常工作(控制台登录"FOUND"),但是当我编写另一个脚本时控制台日志,以查看间隔是否仍在运行.确实如此,它永远不会停止并且 clearInterval
被完全忽略
有什么我想念的吗?我还尝试过使用其他所有解决方案,包括 settimeout
,现在最接近我的是书面解决方案,我只想让 clearinterval
在条件返回true后生效.>
是否有任何类似于 clearinterval
的方法更有效,杀死了整个函数或其他功能?
就目前而言,您的代码是正确的,但是
document.getElementsByTagName("fb:comments")[0] .setAttribute('order_by','social');
引发错误,(当然)超时将永远不会清除.您可以改为使用 SetTimeout
.
最有可能调用 getElementsByTagName("fb:comments")
返回一个空集,给您未定义的元素上不存在方法setAttribute"类型错误.
var timer;
function check_element_load(){
timer = window.setInterval(function(){
console.log("still working"); // keeps running forever
if(document.getElementById("comments")){
console.log("FOUND"); // this actually runs
document.getElementsByTagName("fb:comments")[0].setAttribute('order_by', 'social');
window.clearInterval(timer); // < not effective
}
}, 50);
}
check_element_load();
I'm trying to put a script on top to keep checking if a specific element was successfully loaded in the browser, it works (the console logged " FOUND "), but when I wrote another console log to see if the interval still running. it does, it never stops and the clearInterval
is completely ignored
is there anything that I missed ? I also tried using all other solutions including settimeout
and the closest one to me now is the written, I just want the clearinterval
to take effect after the condition returns true.
Is there anything similar to clearinterval
that is more effective, kills the whole function or something?
As it stands, your code is logical correct, however if
document.getElementsByTagName("fb:comments")[0].setAttribute('order_by', 'social');
throws an error, (of course) the timeout will never be cleared. You could use SetTimeout
instead.
Most likely calling getElementsByTagName("fb:comments")
returns an empty set, giving you an "method setAttribute does not exist on Element undefined" Type Error.
这篇关于clearInterval不会clearInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!