clearInterval doesn't clearInterval

clearInterval doesn't clearInterval

本文关键字:clearInterval doesn      更新时间:2023-09-26
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();

我试图把一个脚本放在顶部,以保持检查是否在浏览器中成功加载了一个特定的元素,它工作(控制台记录"FOUND"),但当我写另一个控制台日志,看看间隔是否仍在运行。它会,它永远不会停止并且clearInterval被完全忽略

有什么我错过了吗?我还尝试使用包括settimeout在内的所有其他解决方案,现在最接近我的解决方案是书面的,我只想让clearinterval在条件返回true后生效。

是否有类似于clearinterval的东西更有效,杀死整个功能或其他什么?

目前看来,您的代码在逻辑上是正确的,但是如果

document.getElementsByTagName("fb:comments")[0].setAttribute('order_by', 'social');

抛出错误,(当然)超时将永远不会被清除。你可以用SetTimeout代替。

很可能调用getElementsByTagName("fb:comments")返回一个空集合,给你一个"method setAttribute does not exist on Element undefined"类型错误