@thmsdmcrt_/looper
Version:
requestAnimationFrame wrapper
210 lines (198 loc) • 6.56 kB
JavaScript
/* Copyright (c) 2018 - Thomas DEMOCRITE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Main Loop Function <Private>. This function context is the Looper instance.
*
* @returns current requestAnimationFrame id
*/
const _OPTIONS = {
debug: false
}
/**
*
*
* @author Thomas Démocrite
* @export
* @class Looper
*/
export class Looper {
/**
* Creates an instance of Looper.
* @author Thomas Démocrite
* @memberof Looper
*/
constructor (opts = {}) {
this.opts = opts || _OPTIONS
this.id = null
this.actions = new Set()
this.actionsLength = 0
this.startTimestamp = null
this.currentTimestamp = null
this.elapsedTimestamp = null
/* Duration parameter */
this.durationTimestamp = null
this.hooks = {}
/* Init */
this.loop = this.loop.bind(this)
this.start = this.start.bind(this)
this.stop = this.stop.bind(this)
this.add = this.add.bind(this)
this.dispose = this.dispose.bind(this)
}
loop () {
this.id = window.requestAnimationFrame(this.loop)
this.currentTimestamp = window.performance.now()
this.elapsedTimestamp = this.currentTimestamp - this.startTimestamp
this.actions.forEach(action => {
if (typeof action === 'function') {
action()
}
})
if (this.hooks.onUpdate) {
let progress = this.elapsedTimestamp / this.durationTimestamp
this.hooks.onUpdate(Math.min(Math.max(progress, 0), 1))
}
if (this.opts.debug) {
let callstackTimestamp = window.performance.now()
if (callstackTimestamp - this.currentTimestamp > 16) {
console.warn(
'The Looper instance callstack actions is to heavy, framerate budget exceeded.'
)
}
}
if (
this.durationTimestamp &&
this.elapsedTimestamp >= this.durationTimestamp
) {
return this.stop()
}
}
/**
* Start the loop function only if the current instance loop function isn't running. Pass an optional duration for a limited in time loop.
*
* @author Thomas Démocrite
* @param {number} Duration in milliseconds
* @param {object} hookMethods an object containing onStart, onUpdate and onStop method if the duration is provided.
* @returns The current Looper instance
* @memberof Looper
*/
start (duration, hookMethods) {
if (!this.isRunning()) {
this.startTimestamp = window.performance.now()
this.currentTimestamp = window.performance.now()
this.elapsedTimestamp = window.performance.now()
if (duration && typeof duration === 'number') {
this.durationTimestamp = duration
if (hookMethods && typeof hookMethods === 'object') {
for (let key in hookMethods) {
if (hookMethods[key] && typeof hookMethods[key] === 'function') {
this.hooks[key] = hookMethods[key]
if (key === 'onStart') this.hooks[key]()
} else {
throw new TypeError(
hookMethods[key] + ' is not a type of function'
)
}
}
}
} else if (duration) {
throw new TypeError(
'the duration argument is not a type of number. Got ' + duration
)
}
this.id = window.requestAnimationFrame(this.loop)
return this
} else if (typeof this.id === 'number') {
console.warn(
'The requestAnimationFrame id is currently define. The loop is running.'
)
console.warn('Please call Looper.stop() method instead.')
}
}
/**
* Stop the current loop function and clear the instance requestAnimationFrame current id.
*
* @author Thomas Démocrite
* @returns <Object> the current Looper instance.
* @memberof Looper
*/
stop () {
if (this.isRunning()) {
window.cancelAnimationFrame(this.id)
if (this.hooks.onStop) this.hooks.onStop()
this.id = null
this.startTimestamp = null
this.currentTimestamp = null
this.elapsedTimestamp = null
this.durationTimestamp = null
this.hooks = {}
} else if (this.id === null || this.id === undefined) {
console.warn(
'The requestAnimationFrame id is null. Avoid useless Looper.stop() call.'
)
} else {
throw new Error(
'The requestAnimationFrame id is not define or is not a number.'
)
}
return this
}
/**
* Detect if the loop function is running or not
*
* @author Thomas Démocrite
* @returns {booleen} isRunning
* @memberof Looper
*/
isRunning () {
return (
(this.id !== undefined || this.id !== null) && typeof this.id === 'number'
)
}
/**
* Add a function to the loop call to performe action.
*
* @author Thomas Démocrite
* @param {object} Function The dedicated action to call during the loop.
* @returns {object} Object factory for removing the added action.
* @memberof Looper
*/
add (func) {
if (!func || typeof func !== 'function' || Array.isArray(func)) {
throw new TypeError('The intended argument is not a type of function.')
}
this.actions.add(func)
this.actionsLength = this.actions.length
return {
remove: _ => {
this.actions.delete(func)
this.actionsLength = this.actions.length
}
}
}
/**
* Clear the instance's actions <Array>, the current requestAnimationFrame id and the loop function.
*
* @author Thomas Démocrite
* @memberof Looper
*/
dispose () {
if (this.isRunning()) this.stop()
this.actions.clear()
}
}