【问题标题】:AW Snap! Google chrome ran out of memory while trying to display web page哦,快!谷歌浏览器在尝试显示网页时内存不足
【发布时间】:2017-09-15 04:34:52
【问题描述】:

我正面临 “糟糕!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>

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

我还在Aw Snap! Google chrome ran out of memory while trying to display web page.上发布了我的观察错误

但在 Google 方面,没有人回复我的应用程序或 google chrome 本身的实际问题。

【问题讨论】:

  • 这是因为您为每个 setTimeout 分配内存但没有清除它们

标签: javascript google-chrome memory-leaks xmlhttprequest out-of-memory


【解决方案1】:

问题是内存中的 n 个 setTimeout。它持有它,然后您会看到收到的错误消息。解决方案是使用一个命名的 timeout 变量,然后在分配一个新变量之前将其从内存中清除。 p>

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。
  • 浏览器崩溃了吗?我也在谷歌浏览器上,它使用的是 45k+,但它仍然运行顺利。所以可能你需要升级内存。
  • 是的,我没有在此应用程序中遇到浏览器崩溃。我的项目出现浏览器崩溃问题。这只是为了说明为什么它会增加内存。因为它不断增加内存而不是恢复。
猜你喜欢
  • 1970-01-01
  • 2017-11-24
  • 2016-01-22
  • 2020-12-11
  • 1970-01-01
  • 2021-07-04
  • 2011-01-06
  • 1970-01-01
  • 2012-08-22
相关资源
最近更新 更多