Skip to content

Instantly share code, notes, and snippets.

@piyush1104
Forked from jakearchibald/1.js
Created February 11, 2021 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piyush1104/5d8dcacab73b6379d11f3ca2471108c2 to your computer and use it in GitHub Desktop.
Save piyush1104/5d8dcacab73b6379d11f3ca2471108c2 to your computer and use it in GitHub Desktop.
export function animationInterval(ms, signal, callback) {
const start = document.timeline.currentTime;
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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment