Last active
October 25, 2017 14:14
-
-
Save radist2s/6a2c46eaa44ed66dc00d to your computer and use it in GitHub Desktop.
Request Animation Frame Queue
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
/** | |
* Using: | |
* var queue = new RafAnimationQueue(defaultContext) | |
* queue.add(firstAnimationFrameCallback) // firstAnimationFrameCallback will executed with defaultContext | |
* queue.add(secondAnimationFrameCallback, customContext) | |
* queue.delay() // skip just one frame | |
* queue.clear() // clear animation queue | |
**/ | |
window.RafAnimationQueue = (function () { | |
function RafAnimationQueue(context) { | |
this.context = context || undefined | |
this.clear() | |
} | |
RafAnimationQueue.prototype.add = function (callback, context) { | |
if (callback instanceof Function) { | |
this.queue.push(callback.bind(context || this.context)) | |
this.runQueue() | |
} | |
return this | |
} | |
RafAnimationQueue.prototype.delay = function () { | |
this.queue.push(undefined) | |
this.runQueue() | |
return this | |
} | |
RafAnimationQueue.prototype.runQueue = function () { | |
if (this.queueInProgress) { | |
return | |
} | |
this.queueInProgress = true | |
requestAnimationFrame(this.queueLoop.bind(this)) | |
} | |
RafAnimationQueue.prototype.queueLoop = function () { | |
var callback = this.queue.shift() | |
callback instanceof Function && callback() | |
if (!this.queue.length) { | |
this.queueInProgress = false | |
} | |
else { | |
requestAnimationFrame(this.queueLoop.bind(this)) | |
} | |
} | |
RafAnimationQueue.prototype.clear = function () { | |
this.queue = [] | |
} | |
return RafAnimationQueue | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment