Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top