export class Loop {
  constructor(update, render) {
    this.update = update;
    this.render = render;
    this.frame = null;
    this.last = 0;
  }

  start() {
    this.stop();
    this.last = performance.now();
    const tick = now => {
      const delta = Math.min((now - this.last) / 1000, 0.05);
      this.last = now;
      this.update(delta);
      this.render();
      this.frame = requestAnimationFrame(tick);
    };
    this.frame = requestAnimationFrame(tick);
  }

  stop() {
    if (this.frame) cancelAnimationFrame(this.frame);
    this.frame = null;
  }
}
