Pages

bind en action

class GameLoop {
  constructor(options) {
    this.options = options;
    this.running = false;
    this.raf = null;
    this.delta = 1000;
    this.accumulator = 0;
    this.last = performance.now();
  }

  start() {
    if (!this.running) {
      this.running = true;
      this.raf = window.requestAnimationFrame(this.tick.bind(this));
      console.log(this.raf);
    }
  }
  stop() {
    this.running = false;
    window.cancelAnimationFrame(this.raf);
   
  }
  tick() {
    let now = performance.now();
    let dt = now - this.last;
    this.last = now;

    this.accumulator += dt;


    while (this.accumulator >= this.delta) {
      if (this.options.render) {
        this.options.render();
      }

      this.accumulator -= this.delta;
    }

    if (true && this.options.update) {
      this.options.update(this.accumulator);
    }

    if (this.running) {
      this.raf = requestAnimationFrame(this.tick.bind(this));
    }
  }
}

let render = function() {
  const posts = [];
  const random = (min, max) => Math.floor(Math.random() * (max - min)) + min
  for (let i = 0; i < 1000; i++) {
    posts.push({
      id: `ID_${i}`,
      upVotes: random(1, 1000)
    });
  }


  console.time("sort after");
  let [c, d] = posts
    .reduce((acc, cur) => [cur, ...acc], [])
    .sort((a, b) => b.upVotes - a.upVotes)
    .slice(0, 2);
  console.timeEnd("sort after");

}
update = (v) => console.log(v);

options = {
  render,
}

let g = new GameLoop(options);
g.start();
window.setTimeout(g.stop,5000);

Impossible d’arrêter la boucle du jeu ?
trouver la faille !