Created
January 15, 2017 10:24
-
-
Save jaz303/4590f845182cc5e3879495668d5d5ca6 to your computer and use it in GitHub Desktop.
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
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