Skip to content

Instantly share code, notes, and snippets.

@batako
Last active April 8, 2019 14:02
Show Gist options
  • Select an option

  • Save batako/784ce7a9ebe1710eef7ffb8a62e8a3fc to your computer and use it in GitHub Desktop.

Select an option

Save batako/784ce7a9ebe1710eef7ffb8a62e8a3fc to your computer and use it in GitHub Desktop.
FPS指定して関数実行
const cancelAnimationFrame = window.cancelAnimationFrame
|| window.mozcancelAnimationFrame
|| window.webkitcancelAnimationFrame
|| window.mscancelAnimationFrame;
let animationHandler = (callback, fps, autoFps) => {
if (!fps) fps = 1;
let basetime = Date.now();
const fpms = 1000/fps;
const requestAnimationFrame = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.setTimeout;
const minSleepTime = 10;
let status = {
animation_id: null
};
const animation = () => {
const now = Date.now();
if( (now - basetime) / fpms >= 1 ) {
basetime = now;
if (autoFps) {
startTime = Date.now();
callback();
endTime = Date.now();
var callbackTime = endTime - startTime;
if ( (fpms - minSleepTime) > callbackTime ) {
fpms = callbackTime + minSleepTime;
}
} else {
callback();
}
}
status.animation_id = requestAnimationFrame(animation, fpms);
}
animation();
return status;
};
// start animation
let status = animationHandler(
() => console.log( Date.now() ),
60
);
// stop animation
cancelAnimationFrame(status.animation_id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment