Skip to content

Instantly share code, notes, and snippets.

@m4n1ok
Last active September 15, 2020 12:06
Show Gist options
  • Save m4n1ok/db71b716467bbea84b9f3cec7f82ae0d to your computer and use it in GitHub Desktop.
Save m4n1ok/db71b716467bbea84b9f3cec7f82ae0d to your computer and use it in GitHub Desktop.
class RAF {
constructor () {
if (!RAF.instance) {
this._radId = null
this._callbacksMap = {}
this._callbacks = []
RAF.instance = this
}
return RAF.instance
}
run () {
this._radId = window.requestAnimationFrame(this.draw.bind(this))
}
draw () {
this._callbacks.forEach(callback => {
callback()
})
this._radId = window.requestAnimationFrame(this.draw.bind(this))
}
stop () {
window.cancelAnimationFrame(this._radId)
this._radId = null
}
add (callback) {
if (typeof callback !== 'function') return false
const index = Date.now()
this._callbacksMap[index] = callback
this._callbacks = Object.values(this._callbacksMap)
if (this._radId) return index
this.run()
return index
}
remove (id) {
if (!this._callbacksMap[id]) return
delete this._callbacksMap[id]
this._callbacks = Object.values(this._callbacksMap)
if (this._callbacks.length === 0) {
this.stop()
}
}
destroy () {
this.stop()
this._callbacks = []
this._callbacksMap = {}
}
}
const instance = new RAF()
export default instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment