Created
September 26, 2025 17:12
-
-
Save greggman/b9bbba0c5cb5b700a1139faea2bb4185 to your computer and use it in GitHub Desktop.
fps using async loop with postMessage based pause
This file contains hidden or 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
/*bug-in-github-api-content-can-not-be-empty*/ |
This file contains hidden or 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
<pre id="count"></pre> | |
<canvas></canvas> |
This file contains hidden or 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
const pause = (function() { | |
let reqId = 0; | |
const reqs = new Map(); | |
window.addEventListener('message', (e) => { | |
const resolve = reqs.get(e.data); | |
if (resolve) { | |
reqs.delete(e.data); | |
resolve(); | |
} | |
}); | |
return _ => new Promise(resolve => { | |
const id = reqId++; | |
reqs.set(id, resolve); | |
window.postMessage(id); | |
}); | |
})(); | |
const r = max => Math.random() * max | 0; | |
const ctx = document.querySelector('canvas').getContext('2d'); | |
function render() { | |
const { width, height } = ctx.canvas; | |
for (let i = 0; i < 1000; ++i) { | |
ctx.fillStyle = `rgb(${r(256)} ${r(256)} ${r(256)})`; | |
ctx.beginPath(); | |
ctx.arc(r(width), r(height), 10 + r(50), 0, Math.PI * 2); | |
ctx.fill(); | |
} | |
} | |
(async function() { | |
const countElem = document.querySelector('#count'); | |
for (;;) { | |
const start = performance.now(); | |
render(); | |
await pause(); | |
const end = performance.now(); | |
countElem.textContent = `fps: ${(1000 / (end - start)).toFixed(4)}`; | |
} | |
})(); |
This file contains hidden or 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
{"name":"fps using async loop with postMessage based pause","settings":{},"filenames":["index.html","index.css","index.js"]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment