Skip to content

Instantly share code, notes, and snippets.

@jaz303
Created January 15, 2017 10:24
Show Gist options
  • Save jaz303/4590f845182cc5e3879495668d5d5ca6 to your computer and use it in GitHub Desktop.
Save jaz303/4590f845182cc5e3879495668d5d5ca6 to your computer and use it in GitHub Desktop.
function createTransport({fps, reset, update, draw}) {
const [UNKNOWN, READY, RUNNING] = enumeration('UNKNOWN', 'READY', 'RUNNING');
const frameLength = Math.floor(1000 / fps);
const clock = {dt: null};
let state = UNKNOWN, timer = null, lastFrame = null, nextFrame = null;
function _start() {
if (state === RUNNING) return;
if (state === UNKNOWN) _reset();
state = RUNNING;
lastFrame = Date.now() - frameLength;
tick();
function tick() {
const frameStart = Date.now();
const nextFrame = frameStart + frameLength;
clock.dt = frameStart - lastFrame;
lastFrame = frameStart;
update(clock);
draw();
timer = setTimeout(tick, nextFrame - Date.now());
}
}
function _stop() {
if (state !== RUNNING) return;
clearTimeout(timer);
timer = null;
state = READY;
}
function _reset() {
_stop();
reset();
state = READY;
}
return {
start: _start,
stop: _stop,
reset: _reset
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment