Skip to content

Instantly share code, notes, and snippets.

@alsotang
Created December 4, 2023 04:23
Show Gist options
  • Save alsotang/e3596524afb6acc24d46e25ca1f0a9c5 to your computer and use it in GitHub Desktop.
Save alsotang/e3596524afb6acc24d46e25ca1f0a9c5 to your computer and use it in GitHub Desktop.
use requestAnimationFrame to calculate frameRate
<body>
<script>
// record every requestAnimationFrame interval and use them to calculate the average framerate.
let frameRate = 0;
let historyInterval = [];
let historyIntervalLength = 200;
let lastTime = Date.now();
requestAnimationFrame(function loop() {
let now = Date.now();
let interval = now - lastTime;
lastTime = now;
historyInterval.push(interval);
if (historyInterval.length > historyIntervalLength) {
historyInterval.shift();
}
frameRate = Math.round(1000 / (historyInterval.reduce((a, b) => a + b) / historyInterval.length));
requestAnimationFrame(loop);
console.log(`frameRate`, frameRate)
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment