Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save WebReflection/989fbba2de277eed4dea to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/989fbba2de277eed4dea to your computer and use it in GitHub Desktop.
A generic requestAnimationFrame batches controller
var AnimationBatch = AnimationBatch || (function(window){
'use strict';
/*! (C) Andrea Giammarchi - Mit Style License */
var
instances = [],
forEach = instances.forEach || function (fn) {
// ad-hoc shim for this use case
var
self = this,
i = 0
;
while (i < self.length) {
fn.call(self, self[i++]);
}
},
indexOf = instances.indexOf || function (value) {
var i = this.length;
while (i-- && value !== this[i]) {}
return i;
},
push = instances.push,
splice = instances.splice,
equestAnimationFrame = 'equestAnimationFrame',
rAF =
window['r' + equestAnimationFrame] ||
window['webkitR' + equestAnimationFrame] ||
window['mozR' + equestAnimationFrame] ||
window['msR' + equestAnimationFrame] ||
window['oR' + equestAnimationFrame] ||
(function(Date){
var
// 30 FPS 'cause old devices won't catch up on 60FPS anyway
interval = 1000 / 30,
max = Math.max,
now = Date.now || function () {
return (new Date).getTime();
},
past = 0,
present, future
;
return function (callback) {
present = now();
future = max(0, interval - (present - past));
setTimeout(callback, future);
past = present + future;
};
}(Date))
,
AnimationBatchPrototype = AnimationBatch.prototype
;
function addIfAbsentFrom(where, what) {
return ~indexOf.call(where, what) ?
0 : push.call(where, what);
}
function cleanUp(self) {
dropFrom(instances, self);
splice.call(self, 0, self.length);
}
function dropFrom(where, what) {
var i = indexOf.call(where, what);
if (~i) splice.call(where, i, 1);
}
function invoke(callback) {
callback.call(this);
}
function loop() {
var
batches = instances.slice(0),
i = 0,
length = batches.length,
batch
;
while (i < length) {
batch = batches[i++];
forEach.call(batch, invoke, batch);
}
if (instances.length) {
rAF(loop);
}
}
function startLoopIfNeeded(self) {
if (addIfAbsentFrom(instances, self)) {
rAF(loop);
}
}
function AnimationBatch() {
if (push.apply(this, arguments)) {
startLoopIfNeeded(this);
}
}
AnimationBatchPrototype.length = 0;
AnimationBatchPrototype.add = function add(fn) {
var self = this;
addIfAbsentFrom(self, fn);
startLoopIfNeeded(self);
return self;
};
AnimationBatchPrototype.abort = function abort(async) {
var self = this;
return async ?
self.add(function () {
cleanUp(self);
}) :
cleanUp(self);
};
AnimationBatchPrototype.remove = function remove(fn) {
var self = this;
dropFrom(self, fn);
if (!self.length) {
dropFrom(instances, self);
}
return self;
};
return AnimationBatch;
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment