Skip to content

Instantly share code, notes, and snippets.

@greggman
Created September 26, 2025 17:12
Show Gist options
  • Save greggman/b9bbba0c5cb5b700a1139faea2bb4185 to your computer and use it in GitHub Desktop.
Save greggman/b9bbba0c5cb5b700a1139faea2bb4185 to your computer and use it in GitHub Desktop.
fps using async loop with postMessage based pause
/*bug-in-github-api-content-can-not-be-empty*/
<pre id="count"></pre>
<canvas></canvas>
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)}`;
}
})();
{"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