Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Created August 27, 2012 00:07
Show Gist options
  • Save nhunzaker/3484542 to your computer and use it in GitHub Desktop.
Save nhunzaker/3484542 to your computer and use it in GitHub Desktop.
JS: requestAnimationFrame Loop Pattern
/*
TIME BASED ANIMATION:
---------------------
To keep things moving at a constant time-based rate instead of varying
frame-based, multiply your movement by APP.deltaTime
BAD: 100 pixels per frame (BOO... movement is tied to framerate)
var velocity = 100;
BETTER: 100 pixels per second (Horray! Framerate independence!)
var velocity = 100 * APP.deltaTime;
EXAMPLE:
thing.x += velocity // moves thing at 100 pixels per second
*/
var APP = APP || {};
APP.update = function() {
// var velocity = 100 * APP.deltaTime;
// thing.x += velocity;
};
// Creating a new function on EVERY frame is expensive. Let's fix that:
APP._frame = function() {
APP.now = Date.now();
APP.delta = APP.now - APP.then;
APP.deltaTime = APP.delta / 1000; // Converts to seconds (optional)
APP.then = APP.now;
APP.update();
APP.loop();
}
APP.loop = function() {
APP.animationFrameLoop = window.requestAnimationFrame(APP._frame);
};
APP.pause = function() {
window.cancelAnimationFrame(APP.animationFrameLoop);
};
APP.resume = function() {
APP.then = Date.now();
APP.loop();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment