Skip to content

Instantly share code, notes, and snippets.

@herrernst
Last active August 11, 2023 10:00
Show Gist options
  • Save herrernst/892c0ff9d1bab94319e1ebfb82204f4d to your computer and use it in GitHub Desktop.
Save herrernst/892c0ff9d1bab94319e1ebfb82204f4d to your computer and use it in GitHub Desktop.
requestAnimationFrame fps loop
<!doctype html>
<meta name="viewport" content="width=device-width">
<style>
:root {
font-family: sans-serif;
background: black;
color: white;
}
#frameInfo, #timeInfo, #fps {
font-size: 5em;
padding: 0.2em;
}
</style>
<button onclick="stop()">stop</button>
<button onclick="start()">start</button>
cur frame in this second: <div id="frameInfo"></div>
cur fps: <div id="fps">0</div>
time secs since load: <div id="timeInfo"></div>
<script>
var currFrame = 0
var nextSec = 1
function fn(time) {
if (time >= nextSec*1000) {
nextSec++;
document.getElementById("fps").textContent = currFrame;
currFrame = 0
}
currFrame++
document.getElementById("frameInfo").textContent = currFrame
document.getElementById("timeInfo").textContent = Math.round(time) / 1000
curId = requestAnimationFrame(fn)
}
var curId = -1
function start() {
stop()
curId = requestAnimationFrame(fn)
}
start()
function stop() {
cancelAnimationFrame(curId)
}
</script>
<address>I'm not sure if FPS and current frame are not off by 1.</address>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment