Last active
July 31, 2022 18:22
-
-
Save rajasharan/bbc7e078db7852bd47d7f6adb112f867 to your computer and use it in GitHub Desktop.
How to calculate FPS using requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// note(): duration to run the test for in µs | |
const TEST_DURATION_US = 5_000_000; | |
let start, prev; | |
let counter = 0; | |
let ith_second = 0; | |
function fps(timestamp) { | |
// note(): convert to µs | |
const uTS = timestamp * 1000; | |
// note(): flag to control the animation | |
let done = false; | |
if (!start) { | |
start = uTS; | |
} | |
const elapsed = uTS - start; | |
// note(): this is to avoid duplicate processing | |
if (prev !== uTS) { | |
// note(): keep counting upto a second | |
const nth_second = parseInt(elapsed / 1_000_000); | |
if (nth_second === ith_second) { | |
counter += 1; | |
} else { | |
// note(): every second print fps and reset counter | |
ith_second = nth_second; | |
console.log(`fps: ${counter}`); | |
counter = 0; | |
} | |
} | |
// note(): stop after a certain duration | |
if (elapsed > TEST_DURATION_US) { | |
done = true; | |
} | |
prev = uTS; | |
if (!done) { | |
window.requestAnimationFrame(fps); | |
} else { | |
console.log('DONE'); | |
} | |
} | |
window.requestAnimationFrame(fps); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment