Created
October 12, 2023 01:07
-
-
Save Nate-Wilkins/91764e55b7b682bdbd350a6208a29a0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Create an animation frame with a specified callback with | |
* a target frame rate. | |
*/ | |
const createAnimationFrame = ( | |
callback, | |
targetFrameRate, | |
timePrevious, | |
timeCurrent, | |
) => { | |
if (typeof timePrevious === 'number' && typeof timeCurrent === 'number') { | |
const timeDelta = timeCurrent - timePrevious; | |
if ( | |
typeof targetFrameRate !== 'number' || | |
timeDelta >= 1000 / targetFrameRate | |
) { | |
const success = callback(timeDelta); | |
if (!success) { | |
return null; | |
} | |
timePrevious = timeCurrent; | |
} | |
} else { | |
timePrevious = timeCurrent; | |
} | |
return window.requestAnimationFrame(timeCurrent => | |
this.createAnimationFrame( | |
callback, | |
targetFrameRate, | |
timePrevious, | |
timeCurrent, | |
), | |
); | |
}; | |
// Usage: | |
createAnimationFrame( | |
timeDelta => { | |
// Do stuff... | |
return true; | |
}, | |
120 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment