clearInterval doesn't clearInterval

扶醉桌前 提交于 2020-04-30 16:32:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15877832/clearinterval-doesnt-clearinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!