Skip to content

Instantly share code, notes, and snippets.

@AfterAllDev
Created November 28, 2024 15:25
Show Gist options
  • Save AfterAllDev/002a0c9e59355dd6c32f5cfdc2129791 to your computer and use it in GitHub Desktop.
Save AfterAllDev/002a0c9e59355dd6c32f5cfdc2129791 to your computer and use it in GitHub Desktop.
Polls refresh rate for a second, once the window has focus, after a 1 second delay, then emits an event called "fpsCheck"
(function (window) {
// Usage:
// document.addEventListener(
// 'fpsCheck',
// (e) => {
// console.log(e.detail);
// }
// );
function measureFps() {
setTimeout(() => {
let fps = 60;
const times = [];
function refreshLoop() {
window.requestAnimationFrame(() => {
const now = performance.now();
times.push(now);
if (now - times[0] <= 1000) {
refreshLoop();
} else {
fps = times.length;
const event = new CustomEvent('fpsCheck', { detail: fps });
// Dispatch the event.
document.dispatchEvent(event);
}
});
}
refreshLoop();
}, 1000);
}
if (document.hidden) {
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
measureFps();
}
});
} else {
measureFps();
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment