哇咔嚓!Google Chrome 在尝试显示网页时内存不足

Sur*_*eek 5 javascript memory-leaks google-chrome xmlhttprequest out-of-memory

我面临“糟糕!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>
Run Code Online (Sandbox Code Playgroud)

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

我还在 Aw Snap 上发布了我观察到的错误!Google Chrome 在尝试显示网页时内存不足。

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

Jai*_*Jai 1

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

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();
}
Run Code Online (Sandbox Code Playgroud)
<div id="time">
  <h1>Time Sample Timer App</h1>
  <button type="button" onclick="getTime()">Start Timer</button>
</div>
Run Code Online (Sandbox Code Playgroud)