【发布时间】:2013-11-24 23:52:33
【问题描述】:
我想测量加载文本需要多少毫秒(取决于我稍后将如何设置它的样式)并进行 10 次测量。我已经把它放在一起,但使用 RequestAnimationCode 似乎不再加载了。
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
var stuff = [];
stuff[0] = new Array( "Text1", "Bla1Bla1Bla1" );
stuff[1] = new Array( "Text2", "Bla2Bla2Bla2Bla2Bla2Bla2Bla2Bla2Bla2Bla2" );
stuff[2] = new Array( "Text3", "Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3Bla3" );
var lastTime = 0;
var count = 10;
var nprint = 50;
var t0 = 0;
var t1 = 0;
//----------------------Start Window loading event---------------------------
$(window).load(function () {
//print links once
$.each(stuff, function(index, out) {
$( "#text" ).append( "<p id='" + out[0] + "'>" + out[0] + " - " + out[1] + "</p>" );
});
//-----------------AnimationFrameMeasure
//loading text 0 50 times
for ( var i = 0; i < nprint; i++ ) {
$( "#testbox" ).append( "<p id='" + stuff[0][0] + "'>" + stuff[0][0] + " - " + stuff[0][1] + "</p>" );
}
function loop(t) {
var diff = lastTime - t;
lastTime = t;
t0 = window.performance.now();
//loading text 50 times
for ( var i = 0; i < nprint; i++ ) {
$( "#testbox" ).append( "<p id='" + stuff[0][0] + "'>" + stuff[0][0] + " - " + stuff[0][1] + "</p>" );
}
// push time
t1 = window.performance.now();
stuff[0].push(t1-t0);
if (count >= 0) {
requestAnimationFrame(loop);
}
count = count - 1;
}
requestAnimationFrame(loop);
//-------------------------print results-----------------------
alert(stuff);
$.each(stuff, function(index, link) {
$.each(link, function(data, value) {
$( "#resultbox" ).append(" | " + value);
});
$( "#resultbox" ).append("<br />");
});
//--------------------------End Window loading even ------------
});
</script>
<body>
<h2>Text Overview</h2>
<div id="text"></div>
<h2>Result Box</h2>
<div id="resultbox"></div>
<h2>TestBox</h2>
<div id="testbox"></div>
</body>
【问题讨论】:
-
我认为问题出在 //-----------------AnimationFrameMeasure。有人看到错误吗?它可能很小,我是盲人
-
count变量永远不会更新,因此count >= 0始终为真,您的循环永远不会停止。 -
顺便看看
window.performance.now(),这是专门用来衡量性能的。 -
Safari 不支持window.performance.now()
-
这是一个 polyfill:gist.github.com/paulirish/5438650.
标签: javascript performance-testing requestanimationframe