我有以下javascript代码,要循环浏览我的服务器上的多个页面(用于数字标牌)。Javascript可能会发生内存泄漏
此代码用于所有页面,并且(此刻)每3秒在页面上循环一次(请参阅超时)。但是,浏览器的内存使用量增长缓慢而稳定。 2小时后,它从192mb使用到436mb使用。由于这是一个Raspberry Pi,只有512MB专用于CPU的内存,因此不太实用。
这段代码中是否有明显的内存泄漏?我自己并不是专家,但由于这些事情一天会运行8-12小时,可能我正在谈论20次/分钟,所以每天需要+/- 9600-14400重新加载。更多,如果它没有得到关闭..
$(document).ready(function() {
versionPage = parseInt(document.getElementById("version").innerHTML);
versionServer = 0
urls = 0;
getVersion();
currentPage = getPage();
getContent();
main();
function getPage() {
page = window.location.href.split("/");
return page[page.length-1];
}
function getVersion() {
$.ajax({
url: "http://localhost/getVersion",
type: "GET",
dataType: "json",
success: function(json) {
console.log("json" + json);
versionServer = json;
if (versionServer != versionPage) {
console.log("Difference!");
}
else {
console.log("Same!");
}
},
});
}
//saves how much urls there are
function getContent() {
$.ajax({
url: "http://localhost/getContent",
type: "GET",
dataType: "json",
success: function(json) {
console.log(json);
urls = json;
},
});
}
//main function loop
function main() {
//check version every
window.setInterval(function() {
getVersion();
if(versionServer != versionPage) {
window.location.href = "http://localhost:5000/1"
}
if(urls != 1) {
nextPage =(parseInt(currentPage) % urls) + 1;
window.location.href = "http://localhost:5000/" + nextPage;
}
}, 3000);
}
});
你用变量污染全局命名空间,似乎没有太多的异步编程经验,但我没有看到任何明显的东西可以解释这种维度的内存增加。也许这是浏览器保持历史和状态(如表单)和/或图像,......这样的事情? (只是猜测)你有没有监测流量,哪些文件被加载,以及它们有多沉重。 – Thomas
他们只是纯html文件,几个div,一些文本,背景颜色。真的很简单。你是对的,我远离一位经验丰富的JS作家。这就是为什么我认为这是我的编程中的东西。所有文件也是本地文件。总是相同的文件,在测试中有3个。 – Lonefish