Skip to content

Instantly share code, notes, and snippets.

@jakearchibald
Last active July 11, 2024 23:52
Show Gist options
  • Save jakearchibald/cb03f15670817001b1157e62a076fe95 to your computer and use it in GitHub Desktop.
Save jakearchibald/cb03f15670817001b1157e62a076fe95 to your computer and use it in GitHub Desktop.
export function animationInterval(ms, signal, callback) {
// 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);
}
// Usage
import { animationInterval } from './1.js';
const controller = new AbortController();
// Create an animation callback every second:
animationInterval(1000, controller.signal, time => {
console.log('tick!', time);
});
// And to stop it:
controller.abort();
@jakearchibald
Copy link
Author

If your thread is blocked, then both setTimeout and requestAnimationFrame callbacks will be delayed. Avoid running long tasks on the UI thread.

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