Created
December 16, 2014 10:43
-
-
Save hogart/db81639300279e52a3fc to your computer and use it in GitHub Desktop.
Takes two function, one for state `update` and one for `render` that state, and organizes them into animation loop.
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
/** | |
* @author Konstantin Kitmanov <doctor.hogart@gmail.com> | |
* @license MIT | |
*/ | |
(function (root, factory) { | |
if (typeof define === 'function' && define.amd) { // AMD anonymous module | |
define([], factory); | |
} else if (typeof exports === 'object') { // NodeJS/CommonJS-like module | |
module.exports = factory(); | |
} else { // Browser globals (root is window) | |
root.aniLoop = factory(); | |
} | |
}(this, function () { | |
'use strict'; | |
/** | |
* Takes two function, one for state `update` and one for `render` that state, | |
* and organizes them into animation loop. | |
* First, `update` is called and is passed `time` as in requestAnimationFrame and deltaTime from previous tick. | |
* Any value returned from `update` gets passed to `render`. | |
* Returned is a function which stops the loop. | |
* @param {Function} update Updates some state, could return some state | |
* @param {Function} render Renders state returned from `update` | |
* @return {Function} Call this function to stop loop, i.e next iteration won't be requested. | |
*/ | |
function aniLoop (update, render) { | |
var prevTime = 0; | |
var currentRequest; | |
var onRAF = function (time) { | |
var deltaTime = time - prevTime; | |
var state = update(time, deltaTime); | |
render(state); | |
currentRequest = requestAnimationFrame(onRAF); | |
prevTime = time; | |
}; | |
currentRequest = requestAnimationFrame(onRAF); | |
return function () { | |
cancelAnimationFrame(currentRequest); | |
} | |
} | |
return aniLoop; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment