Skip to content

Instantly share code, notes, and snippets.

@ooflorent
Last active August 29, 2015 14:05
Show Gist options
  • Save ooflorent/dc9fd800e14b8ae60f99 to your computer and use it in GitHub Desktop.
Save ooflorent/dc9fd800e14b8ae60f99 to your computer and use it in GitHub Desktop.
Helper for `requestAnimationFrame`

raf

Little browserify helper for requestAnimationFrame.
Down to ~240 bytes when minified.
Down to ~180 bytes when gzipped.

Usage

var raf = require('./raf');
var id = raf.start(function(elapsed) {
  // Called every frames
  game.update(elapsed);
});

API

raf.start(fn)

Calls fn on every frame with elapsed set to the elapsed time in milliseconds. Returns the request ID.

raf.stop(id)

Cancels the specified animation frame request.

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2014 Florent Cailhol <https://github.com/ooflorent>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
// Holds last iteration timestamp.
var time = 0;
/**
* Calls `fn` on next frame.
*
* @param {Function} fn The function
* @return {int} The request ID
* @api private
*/
function raf(fn) {
return window.requestAnimationFrame(function() {
var now = Date.now();
var elapsed = now - time;
if (elapsed > 999) {
elapsed = 1 / 60;
} else {
elapsed /= 1000;
}
time = now;
fn(elapsed);
});
}
module.exports = {
/**
* Calls `fn` on every frame with `elapsed` set to the elapsed
* time in milliseconds.
*
* @param {Function} fn The function
* @return {int} The request ID
* @api public
*/
start: function(fn) {
return raf(function tick(elapsed) {
fn(elapsed);
raf(tick);
});
},
/**
* Cancels the specified animation frame request.
*
* @param {int} id The request ID
* @api public
*/
stop: function(id) {
window.cancelAnimationFrame(id);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment