Last active
December 22, 2022 20:39
-
-
Save itacirgabral/ec6423c6690d57e6383f903c304c80d8 to your computer and use it in GitHub Desktop.
async await generator loop for 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
async function* asyncAnimationFrame () { | |
const h = {} | |
h.promise = new Promise(r => h.resolve = r) | |
h.flipFrame = () => { | |
h.resolve() | |
h.promise = new Promise(r => h.resolve = r) | |
} | |
try { | |
while (true) { | |
h.idAF = requestAnimationFrame(h.flipFrame) | |
yield await h.promise | |
} | |
} finally { | |
h.resolve() | |
cancelAnimationFrame(h.idAF) | |
} | |
} | |
// example | |
(async () => { | |
const flamer = asyncAnimationFrame() | |
let flag = 0 | |
let now = Date.now() | |
let bef | |
while (flag < 100) { | |
await flamer.next() | |
bef = now | |
now = Date.now() | |
flag++ | |
console.log(now - bef) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://beta.observablehq.com/@itacirgabral/asyncanimationframe