setInterval、ajax 并用引发的内存漏泄
这两天在做一个小功能:通过 setInterval 定时通过 ajax 从后台获取最新数据,再更改浏览器标题,并通过走马灯的方式显示出来。具体代码如下:
(function()
{
titleMain();
var id=window.setInterval(titleMain,10000);
var id2;
function titleMain()
{
//console.log(id);
//console.log(id2);
if(id2!=undefined)
{
window.clearInterval(id2);
}
$.ajax({
type: "POST",
url: "__URL__/ajaxTitle/",
success: success
});
}
function success(title)
{
var num = title.length,i = 0;
id2=window.setInterval(titleHandle,200);
//console.log("id2:"+id2);
function titleHandle()
{
if(i>num)
return (i=0);
document.title = title.substr(i);
i++;
}
}
})();
{
titleMain();
var id=window.setInterval(titleMain,10000);
var id2;
function titleMain()
{
//console.log(id);
//console.log(id2);
if(id2!=undefined)
{
window.clearInterval(id2);
}
$.ajax({
type: "POST",
url: "__URL__/ajaxTitle/",
success: success
});
}
function success(title)
{
var num = title.length,i = 0;
id2=window.setInterval(titleHandle,200);
//console.log("id2:"+id2);
function titleHandle()
{
if(i>num)
return (i=0);
document.title = title.substr(i);
i++;
}
}
})();
功能要实现起来并不难,但有个问题就是存在内存漏泄。一开始我怀疑是第二个套用的 setInterval 引起的,于是将那部分相关的代码注释掉。再观察内存变化情况,同样存在刚才所说的内存问题。
很明显示是不断重复执行 ajax 引起的。自己找不出解决的办法,于是 google 看是否也有人遇到我这样的情况的。找到一篇文章说是 ajax 创建时 new ActiveXObject 导致内存不断增长的(Link)。文中所说的方法是将 ajax 缓存起来,这样就不用每次都创建 new ActiveXObject 对象了,由于我用的代码是 jquery 框架里的,不知怎样缓存。再是决定用原生 javascript 来实现。修改后代码如下:
(function()
{
var ajax = createAjax();
titleMain();
var id=window.setInterval(titleMain,10000);
var id2;
function titleMain()
{
//console.log(id);
//console.log(id2);
if(id2!=undefined)
{
window.clearInterval(id2);
}
ajax.open("POST", "__URL__/ajaxTitle/", true);
ajax.onreadystatechange = success;
ajax.send(null);
}
function success()
{
if (ajax.readyState == 4)
{
if (ajax.status == 200)
{
//return;
//alert(ajax.responseText);
var title = ajax.responseText;
var num = title.length,i = 0;
function titleHandle()
{
if(i>num)
return (i=0);
document.title = title.substr(i);
if(window.parent!=undefined)
window.parent.document.title = document.title;
i++;
}
id2=window.setInterval(titleHandle,200);
//console.log("id2:"+id2);
}
}
}
})();
{
var ajax = createAjax();
titleMain();
var id=window.setInterval(titleMain,10000);
var id2;
function titleMain()
{
//console.log(id);
//console.log(id2);
if(id2!=undefined)
{
window.clearInterval(id2);
}
ajax.open("POST", "__URL__/ajaxTitle/", true);
ajax.onreadystatechange = success;
ajax.send(null);
}
function success()
{
if (ajax.readyState == 4)
{
if (ajax.status == 200)
{
//return;
//alert(ajax.responseText);
var title = ajax.responseText;
var num = title.length,i = 0;
function titleHandle()
{
if(i>num)
return (i=0);
document.title = title.substr(i);
if(window.parent!=undefined)
window.parent.document.title = document.title;
i++;
}
id2=window.setInterval(titleHandle,200);
//console.log("id2:"+id2);
}
}
}
})();
这样修改后再通过 sIEve 来查看内存泄漏情况(如下图),我观察了很长时间都没有发现内存的大幅增加,只是比较平稳的增加一点点。由此可以得出结论这个问题已经得到比较好的解决。