setInterval with auto-clearInterval

1

I'm creating a way to extract data from Twitter without being quoted with their API values. The best way I found it was by using the widget that they make available (and that has no quota) and from their upload I "pick up the information" and treat it.

My problem is that I can not think of a way to make the page check for a tag in the body element that Twitter creates after it loads [data-twttr-rendered=true] .

I tried to make a setInterval by analyzing if this exists and, if it exists, it executes a function and as callback already executes its own clearInterval like this:

var twitter = setInterval(function(){
    if($('body[data-twttr-rendered=true]').length != 0){
        page.twitter.mutage(function(){clearInterval(twitter)});
    }
},1000);

The problem that when running such a code I can bugar the DOM and crash the whole site ...
Does anyone have a better answer for me please?

    
asked by anonymous 18.02.2015 / 01:47

1 answer

2

The reason the site "hangs" is because it is probably generating countless calls from setInterval .

The setInterval never stops unless it is called clearInterval , other than setTimeout than for after the process.

Your code is probably running several times this is part of:

var twitter = setInterval(function(){
...
},1000);

In other words, several "events" are running at the same time and are probably being created new until the browser can not handle.

You can do two things:

  • Use setTimeout instead of setInterval , since the first one expects the event to end other than setInterval .
  • Create a check if your code is already running, you can use the%
  • The code should look something like:

    var exec;
    var twitter = null;
    var initiate = function () {
        if (twitter === null) {//Se a variavel for null então executa, se não previne executar mais de uma vez
            var exec = function () {
                if($('body[data-twttr-rendered=true]').length !== 0){
                    page.twitter.mutage(function(){
                        //...Código pode ser chamado, não necessita de window.clearTimeout
                    });
                } else {
                    //Se não encontrar o atributo data-twttr-rendered=true em body então executa novamente
                    twitter = window.setTimeout(exec, 1000);
                }
            };
            exec();
        }
    };
    initiate();//Inicia o event
    

    MutationObserver

    Another method you can use is twitter , but how do you is using jQuery, so I'll give you a plugin that does a similar job, it's jQuery-Observer .

    var bodyDetect = $('body');
    bodyDetect.observe({
        "attributes": true,
        "attributeFilter": ['data-twttr-rendered']
    }, function(record) {
        page.twitter.mutage(function () {
            //...Código pode ser chamado
        });
    });
    
        
    18.02.2015 / 02:03