Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Last active July 8, 2021 08:10
Show Gist options
  • Save socheatsok78/e0f63fa97cd872e207340c367c7d97f8 to your computer and use it in GitHub Desktop.
Save socheatsok78/e0f63fa97cd872e207340c367c7d97f8 to your computer and use it in GitHub Desktop.
export function animationInterval (ms, callback) {
const controller = new AbortController()
const signal = controller.signal
// Prefer currentTime, as it'll better sync animtions queued in the
// same frame, but if it isn't supported, performance.now() is fine.
const start = document.timeline
? document.timeline.currentTime
: performance.now()
function frame (time) {
if (signal.aborted) return
callback(time)
scheduleFrame(time)
}
function scheduleFrame (time) {
const elapsed = time - start
const roundedElapsed = Math.round(elapsed / ms) * ms
const targetNext = start + roundedElapsed + ms
const delay = targetNext - performance.now()
setTimeout(() => requestAnimationFrame(frame), delay)
}
scheduleFrame(start)
return () => {
controller.abort()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment