Skip to content

Instantly share code, notes, and snippets.

@itacirgabral
Last active December 22, 2022 20:39
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itacirgabral/ec6423c6690d57e6383f903c304c80d8 to your computer and use it in GitHub Desktop.
Save itacirgabral/ec6423c6690d57e6383f903c304c80d8 to your computer and use it in GitHub Desktop.
async await generator loop for requestAnimationFrame
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)
}
})()
@itacirgabral
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment