| 9 | const FPS = 100 / 6 / 2; |
| 10 | |
| 11 | export class FrameLoop { |
| 12 | rafId = 0; |
| 13 | queue = new Set<Function>(); |
| 14 | running = false; |
| 15 | time = { |
| 16 | start: 0, |
| 17 | delta: 0, |
| 18 | elapsed: 0, |
| 19 | _elapsed: 0, |
| 20 | }; |
| 21 | onDemand = false; |
| 22 | |
| 23 | tick() { |
| 24 | if (!this.running) { |
| 25 | return; |
| 26 | } |
| 27 | this.update(); |
| 28 | this.rafId = window.requestAnimationFrame(this.tick.bind(this)); |
| 29 | } |
| 30 | |
| 31 | update() { |
| 32 | if (!this.running) { |
| 33 | return; |
| 34 | } |
| 35 | this.updateTime(); |
| 36 | this.queue.forEach((cb) => cb()); |
| 37 | } |
| 38 | |
| 39 | run() { |
| 40 | if (!this.running) { |
| 41 | this.time = { start: now(), elapsed: 0, delta: 0, _elapsed: 0 }; |
| 42 | this.running = true; |
| 43 | if (!this.onDemand) { |
| 44 | // we need elapsed time to be > 0 on the first frame |
| 45 | this.rafId = window.requestAnimationFrame(this.tick.bind(this)); |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | start(cb: Function) { |
| 51 | this.queue.add(cb); |
| 52 | this.run(); |
| 53 | } |
| 54 | |
| 55 | stop(cb: Function) { |
| 56 | if (!cb) { |
| 57 | return; |
| 58 | } |
| 59 | this.queue.delete(cb); |
| 60 | if (!this.queue.size) { |
| 61 | this.stopAll(); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | stopAll() { |
| 66 | if (this.rafId) window.cancelAnimationFrame(this.rafId); |
| 67 | |
| 68 | this.running = false; |
nothing calls this directly
no outgoing calls
no test coverage detected