Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Call a function with a specific FPS. Exposes methods to pause, start and destroy the looper. Uses ES6.
/**
* @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
You can’t perform that action at this time.