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
檔案,内容如下:
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>