我在使用 requestAnimationFrame() 时遇到了性能问题。
考虑以下代码。这是一个简单的循环,每次时间增量大于 20 毫秒时,都会打印自上一帧以来的时间。
const glob_time_info = {delta_time: 0.0, last_frame: performance.now()};
var render = function (timestamp) {
glob_time_info.delta_time = timestamp - glob_time_info.last_frame;
glob_time_info.last_frame = timestamp;
if(glob_time_info.delta_time > 20)
console.log(glob_time_info.delta_time);
requestAnimationFrame(render);
};
render(performance.now());
据我了解,requestAnimationFrame 这段代码永远不应该打印任何内容,因为它尝试每秒运行 60 次(我的显示器为 60Hz)。 因此时间增量应始终在 16-17 毫秒左右。
但它每隔几秒打印一次大约 33 毫秒的时间。 为什么?
我在使用 Chrome 54 和 Firefox 49 的 Windows 10 上遇到过这种情况。我拥有一台 i5-6600
<小时/>更新 这是 Windows 和 ubuntu 的 Nit 脚本的输出。 window ,你在做什么? Windows 10(电脑): WIndows 8(与下面相同的上网本): Ubuntu(与上面相同的上网本):
最佳答案
很容易检验您的假设,即问题与您所运行的平台有关 - 衡量性能。
简而言之,按照与您的操作类似的方式运行 requestAnimationFrame
多次,并记下每次运行的时间戳。之后,简单地可视化结果。
var times = [];
var measure = function() {
times.push(new Date().getTime());
if (times.length > 100) return draw();
requestAnimationFrame(measure);
};
var draw = function() {
var dataset = {
x: [],
y: [],
type: 'bar'
};
var layout = {
xaxis: {
title: 'measurement #'
},
yaxis: {
title: 'iteration duration (ms)'
},
height: 250
};
var options = {
displayModeBar: false
};
times.reduce(function(previous, current, i) {
dataset.x.push(i);
dataset.y.push(current - previous);
return current;
}, times.shift());
Plotly.newPlot('target', [dataset], layout, options);
}
measure();
#target {
margin-top: -50px;
}
<script src="https://cdn.plot.ly/plotly-1.2.0.min.js"></script>
<div id="target"></div>
您可以在不同操作系统和不同浏览器上运行相同的模拟,看看是否可以进一步缩小问题范围。
关于javascript - requestAnimationFrame() 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538328/