Skip to content

Instantly share code, notes, and snippets.

@radist2s
Last active October 25, 2017 14:14
Show Gist options
  • Save radist2s/6a2c46eaa44ed66dc00d to your computer and use it in GitHub Desktop.
Save radist2s/6a2c46eaa44ed66dc00d to your computer and use it in GitHub Desktop.
Request Animation Frame Queue
/**
* 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