Skip to content

Instantly share code, notes, and snippets.

@x7c1
Created November 9, 2017 15:18
Show Gist options
  • Select an option

  • Save x7c1/474bf26a172153c4031932096d7c65d5 to your computer and use it in GitHub Desktop.

Select an option

Save x7c1/474bf26a172153c4031932096d7c65d5 to your computer and use it in GitHub Desktop.
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