Darn! Google chrome ran out of memory when trying to display a webpage

I ran into "Aw snap! Google chrome ran out of memory when trying to display a webpage".

Below is my simple application to call the API every second. After each call, the chrome memory allocation size for this tab increases continuously. But without diminishing this memory. In the latter case, this causes the page to crash.

 <!DOCTYPE html>
    <html>
    <body>

    <div id="time">
    <h1>Time Sample Timer App</h1>
    <button type="button" onclick="getTime()">Start Timer</button>
    </div>

    <script>

    function getTime() {

     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("time").innerHTML =
          JSON.parse(this.responseText).time;
          setTimeout(getTime, 1000);
        }
      };
      xhttp.open("GET", "http://date.jsontest.com", true);
      xhttp.send();
    }
    </script>
    </body>
    </html>

      

Please help me figure out the reason for this.

I also posted a bug of my observation on Aw Snap! Google chrome ran out of memory when trying to display a webpage.

But from google side no one is answering what is the actual problem with my app or google chrome itself.

+3


source to share


1 answer


Ok, the problem is n number of setTimeout in memory. He holds it down and then an error message appears. The solution is to use a variable called timeout and just clear it out of memory before assigning a new one .



var time; // declare a time
function getTime() {
  if (time) {
    clearTimeout(time);
  } // clear if there is any prev setTimeout running
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("time").innerHTML = JSON.parse(this.responseText).time;
      time = setTimeout(getTime, 1000); // assign a new setTimeout
    }
  };
  xhttp.open("GET", "http://date.jsontest.com", true);
  xhttp.send();
}
      

<div id="time">
  <h1>Time Sample Timer App</h1>
  <button type="button" onclick="getTime()">Start Timer</button>
</div>
      

Run codeHide result


+1


source







All Articles