Created
April 22, 2017 05:34
-
-
Save VitorLuizC/3a9b115d540714375d8fb9d657ce2b21 to your computer and use it in GitHub Desktop.
Simple way to handle a animation loop
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
| /** | |
| * @typedef Animation | |
| * @property {function} animation | |
| */ | |
| /** | |
| * Create a new animation object. | |
| * @param {function} animation | |
| * @returns {Animation} | |
| */ | |
| function animate(animation) { | |
| const instance = { | |
| animation, | |
| id: null | |
| } | |
| return { | |
| get animation() { | |
| return instance.animation | |
| }, | |
| set animation(animation) { | |
| instance.animation = animation | |
| }, | |
| stop: stop.bind(instance), | |
| start: start.bind(instance) | |
| } | |
| } | |
| /** | |
| * Stop animation. Returns false if animation is not running. | |
| * @memberof Animation | |
| * @returns {boolean} | |
| */ | |
| function stop() { | |
| if (this.id === null) // Stopped animation | |
| return false | |
| cancelAnimationFrame(this.id) | |
| this.id = null | |
| return true | |
| } | |
| /** | |
| * Start animation. Returns false if animation is already running. | |
| * @memberof Animation | |
| * @returns {boolean} | |
| */ | |
| function start() { | |
| if (this.id !== null) // Already running animation | |
| return false | |
| this.id = requestAnimationFrame(this.animation) | |
| run.call(this) | |
| return true | |
| } | |
| /** | |
| * Run animation using browser's AnimationFrame API. | |
| * @private | |
| */ | |
| function run() { | |
| this.animation() | |
| this.id = requestAnimationFrame(run.bind(this)) | |
| } | |
| export default animate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment