AW Snap! Google Chrome在尝试显示网页时内存不足。

5

我遇到了"噢,不!Google Chrome在尝试显示网页时已耗尽内存。"

以下是我的一个简单应用程序,每秒钟都会调用一个API。每次调用后,Chrome标签页的内存分配大小会持续增加。但是这些内存不会减少,最后就会导致页面崩溃。

 <!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>

请帮我找出这个问题的根本原因。

我也在Google Chrome上报告了一个错误,显示“噼啪声!谷歌浏览器尝试显示网页时内存不足”。

但是从谷歌方面来看,没有人回复我的应用程序或谷歌浏览器本身存在什么实际问题。


1
这是因为您为每个setTimeout分配了内存,但没有清除它们。 - FrankCamara
你解决了这个问题吗? - Jayrag Pareek
1个回答

1
问题在于内存中的n个setTimeout。它保留了它,然后你看到了你得到的错误消息。解决方案是使用一个命名的timeout变量,并在分配新的timeout之前清除它。

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>


它仍然增加内存,从10000K开始,在2分钟内达到12000K。 - Suraj Pareek
浏览器崩溃了吗?我也在使用谷歌浏览器,它正在使用45k+,但仍然可以顺畅地工作。所以可能你需要升级内存。 - Jai
是的,在这个应用程序中我没有遇到浏览器崩溃的问题。但是在我的项目中,我遇到了浏览器崩溃的问题。这只是为了演示为什么内存使用量会增加,因为它会持续增加而不会回复。 - Suraj Pareek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接