Created
June 26, 2014 18:12
-
-
Save hayes/348246e0060b93077b34 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module.exports = Batch | |
function Batch(sync) { | |
if(!(this instanceof Batch)) { | |
return new Batch(sync) | |
} | |
this.jobs = [] | |
this.sync = sync | |
this.frame = null | |
this.run = this.run.bind(this) | |
} | |
Batch.prototype.request_frame = request_frame | |
Batch.prototype.queue = queue | |
Batch.prototype.add = add | |
Batch.prototype.run = run | |
function add(fn) { | |
var queued = false | |
, batch = this | |
, self | |
, args | |
return queue | |
function queue() { | |
args = [].slice.call(arguments) | |
self = this | |
if(!queued) { | |
queued = true | |
batch.queue(run) | |
} | |
} | |
function run() { | |
queued = false | |
fn.apply(self, args) | |
} | |
} | |
function queue(fn) { | |
this.jobs.push(fn) | |
if(!this.sync) { | |
this.request_frame() | |
} | |
} | |
function run() { | |
var jobs = this.jobs | |
this.jobs = [] | |
this.frame = null | |
for(var i = 0, l = jobs.length; i < l; ++i) { | |
jobs[i]() | |
} | |
} | |
function request_frame() { | |
if(this.frame) { | |
return | |
} | |
this.frame = requestAnimationFrame(this.run) | |
} | |
function requestAnimationFrame(callback) { | |
var raf = global.requestAnimationFrame || | |
global.webkitRequestAnimationFrame || | |
global.mozRequestAnimationFrame || | |
timeout | |
return raf(callback) | |
function timeout(callback) { | |
return setTimeout(callback, 1000 / 60) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment