gpt4 book ai didi

javascript - 哇咔嚓!谷歌浏览器在尝试显示网页时内存不足

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:25:55 26 4
gpt4 key购买 nike

我正面临“糟糕!谷歌浏览器在尝试显示网页时内存不足。”

下面是我每秒调用一个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 本身的实际问题是什么。

最佳答案

问题是内存中的 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();
}
<div id="time">
<h1>Time Sample Timer App</h1>
<button type="button" onclick="getTime()">Start Timer</button>
</div>

关于javascript - 哇咔嚓!谷歌浏览器在尝试显示网页时内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43487389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com