Created
November 9, 2017 15:18
-
-
Save x7c1/474bf26a172153c4031932096d7c65d5 to your computer and use it in GitHub Desktop.
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
| export class Animator { | |
| constructor() { | |
| this._current = 0; | |
| this._running = false; | |
| this._interval = 200;// [msec] | |
| } | |
| run({ from, to, onTick, onFinish }) { | |
| if (this._running) { | |
| this._cancelAnimation(); | |
| } | |
| this._startTime = this._now(); | |
| const evaluate = duration => { | |
| const length = to - from; | |
| return (length / this._interval) * duration; | |
| }; | |
| const main = () => { | |
| this._running = true; | |
| onTick(from + this._current); | |
| const duration = this._now() - this._startTime; | |
| this._current = evaluate(duration); | |
| if (duration >= this._interval) { | |
| this._cancelAnimation(); | |
| this._running = false; | |
| onFinish(to); | |
| } else { | |
| this._animationId = window.requestAnimationFrame(main); | |
| } | |
| }; | |
| main(); | |
| } | |
| _now() { | |
| return window.performance.now(); | |
| } | |
| _cancelAnimation() { | |
| cancelAnimationFrame(this._animationId); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment