Last active
October 12, 2023 01:20
-
-
Save Nate-Wilkins/790c49d030953fca84b1f467010a0b14 to your computer and use it in GitHub Desktop.
createAnimationFrame.ts
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: (timeDelta: number) => boolean, | |
targetFrameRate?: number, | |
timePrevious?: number, | |
timeCurrent?: number, | |
): null | number => { | |
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