Window.requestAnimationFrame()
贴一下MSDN的说明:
The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
//大致意思是: requestAnimationFrame()的参数是一个回调函数, 浏览器引擎会在下一次的页面重绘之前调用它;
使用原生JS来测试一下本地机器的FPS:
1. 创建一个test.html
文件,内容如下:
<div>
当前FPS: <span id="fps"></span><br>
<button onclick="showFPS('fps')">点我开始测试FPS</button>
</div>
<script>
function showFPS(id) {
let requestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
let st = Date.now();
let tt;
let fps = 0;
let frame = 0;
let calcFPS = function () {
(function loop() {
tt = Date.now()
if (tt > st + 1000) {
fps = Math.round((frame * 1000) / (tt - st));
st = Date.now();
frame = 0;
document.getElementById(id).innerHTML = fps;
}
frame++;
requestAnimationFrame(loop);
})();
}
calcFPS();
}
</script>