Skip to content

Instantly share code, notes, and snippets.

@thysultan
Forked from thebuilder/frameLoop.js
Created August 27, 2016 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thysultan/c61272dc8869e3c6f29c2bce034d2c23 to your computer and use it in GitHub Desktop.
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.
/**
* @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