Ajax request with blinking setInterval

2

The following piece of code is intended to put the contents of a text file within a div. Because the text file can be upgraded, that the div is updated with the latest content of the file. But every 2 seconds the div content flashes. How can I achieve the same goal without the content of the div blinking? Thank you.

<script type="text/javascript">
   setInterval("loadXMLDoc()",2000);
   function loadXMLDoc(){
        var xmlhttp;
       // codigo para IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
       xmlhttp.onreadystatechange=function(){
           document.getElementById("minhaDiv").innerHTML=xmlhttp.responseText;
       }
      xmlhttp.open("GET","ajax_doc.txt",true);
      xmlhttp.send();
   }
 </script>
    
asked by anonymous 22.02.2015 / 00:47

1 answer

1

@John, I ran some tests here, the problem occurred when innerHTML was replaced by a Long text.

To circumvent this situation, I did the following.

  • I created a div called container
  • I added the Text to div container
  • I cleaned% with%% with%
  • I added div minhaDiv to div container
  • For the demo below, I used the BaconIpsum API to generate random text.

    setInterval(loadXMLDoc,2000);
    
    var minhaDiv = document.getElementById("minhaDiv");
    function loadXMLDoc(){
        var xmlhttp;
        // codigo para IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.responseText && xmlhttp.responseText.length > 0)
            {   
                var content = document.createElement("div");            
                var paragrafos = JSON.parse(xmlhttp.responseText);
                for (var i = 0; i < paragrafos.length; i++) {
                    var paragrafo = document.createElement("p");                
                    paragrafo.innerHTML = paragrafos[i];
                    content.appendChild(paragrafo);         
                }
            
                if (minhaDiv.firstChild){
                    minhaDiv.removeChild(minhaDiv.firstChild);
                }
                minhaDiv.appendChild(content);
            }
        }
        xmlhttp.open("GET","http://baconipsum.com/api/?type=all-meat&paras=10&start-with-lorem=1",true);
        xmlhttp.send();
    }
    <div id="minhaDiv">
    </div>
        
    22.02.2015 / 02:00