在编写脚本时,我发现我的ajax调用次数比预期多了10倍,于是我添加了一个“fps计数器”,发现Chrome每秒运行约130次,而IE/FF/Opera每秒只运行约35帧。使用以下设置:
function load(){
//other code that does not effect this
requestAnimFrame(function(){
load();
});
debug();//function i was using to catch fps
}
window.requestAnimFrame = (function(callback){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 100);
};
})();
现在的Google Chrome似乎不关心我放入window.setTimeout(callback, 100);中的值,可以是1,也可以是10000000,它都以约130帧运行,其余部分似乎足够接近(始终约为预期的3倍)。 我已经确保我没有多次调用load()。
另一方面,我曾经使用setTimeout(load,100); 当我改用这种方式时,所有浏览器开始以约30fps运行。
function load(){
//other code that does not effect this
debug();//function i was using to catch fps
setTimeout(load, 100);
}
这样做是不好的惯例还是过时了吗?问题是我并不确定为什么要使用requestAnimFrame,除了所有我在网上找到的示例都使用它,并且似乎可以实现给定的目标。我一遍又一遍地触发load事件只是为了检查是否有新信息要传输。
编辑:对于未来阅读此内容的人,请注意。在逐行运行代码时,我发现了一个逻辑错误,这解释了我的三倍时间。我确保没有多次调用load()函数。
function connected(result){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//code that does not matter for this
}else if (xmlhttp.status==404){
alert("epic failure i lost the page");
}
d_time = new Date().getTime();
load();
}
Connect被xmlhttp.onreadystatechange=connected调用,因此它可以多次触发运行3组load(); 我需要做的是:
function connected(result){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
d_time = new Date().getTime();
load();
}else if (xmlhttp.status==404){
alert("epic failure i lost the page");
}
}
所以Schmit和Patrick都在这里提供了帮助。Schmit让我知道我是个新手并且做错了。Patrick帮我意识到了那个函数发生了什么。