-
-
Save thysultan/c61272dc8869e3c6f29c2bce034d2c23 to your computer and use it in GitHub Desktop.
Call a function with a specific FPS. Exposes methods to pause, start and destroy the looper. Uses ES6.
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
/** | |
* @param fn {Function} Callback function to trigger on frame | |
* @param fps {int} Target FPS | |
* @returns {{pause: pause, start: start, destroy: destroy}} | |
*/ | |
function frameLoop(fn, fps=60) { | |
let then = 0; | |
let interval = 1000 / fps; | |
let isRunning = true; | |
let currentFrameId = null; | |
//Start the loop | |
loop(); | |
function loop(time=0) { | |
if (!isRunning) return; | |
currentFrameId = requestAnimationFrame(loop); | |
let delta = time - then; | |
if (delta > interval) { | |
then = time - (delta % interval); | |
fn(); | |
} | |
} | |
function start() { | |
if (isRunning || fn == null) return; | |
isRunning = true; | |
loop(); | |
} | |
function pause() { | |
if (!isRunning) return; | |
isRunning = false; | |
if (currentFrameId) { | |
cancelAnimationFrame(currentFrameId); | |
currentFrameId = null; | |
} | |
} | |
function destroy() { | |
pause(); | |
fn = null; | |
} | |
return { | |
pause, | |
start, | |
destroy | |
} | |
} | |
export default frameLoop; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment