|
| 1 | +import { Event } from "./event.js"; |
| 2 | +import { print } from "./utils.js"; |
| 3 | + |
| 4 | + |
| 5 | +class Interval { |
| 6 | + totalTick = 1; |
| 7 | + executed = false; |
| 8 | + constructor(callback, interval, once) { |
| 9 | + this.callback = callback; |
| 10 | + this.interval = interval; |
| 11 | + this.once = once; |
| 12 | + } |
| 13 | + isRemovable() { |
| 14 | + return this.once && this.executed; |
| 15 | + } |
| 16 | + tick() { |
| 17 | + if(this.totalTick++ % this.interval === 0) { |
| 18 | + this.callback(); |
| 19 | + this.executed = true; |
| 20 | + } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +class IntervalHandler { |
| 25 | + intervals = {}; |
| 26 | + intervalID = 0; |
| 27 | + tick() { |
| 28 | + for(const id in this.intervals) { |
| 29 | + const interval = this.intervals[id]; |
| 30 | + interval.tick(); |
| 31 | + if(interval.isRemovable()) { |
| 32 | + this.remove(id); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + add(interval) { |
| 37 | + const id = this.intervalID++; |
| 38 | + this.intervals[id] = interval; |
| 39 | + return id; |
| 40 | + } |
| 41 | + remove(id) { |
| 42 | + delete this.intervals[id]; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +export const Tick = new (class { |
| 47 | + #intervalHandler = new IntervalHandler(); |
| 48 | + |
| 49 | + constructor() { |
| 50 | + Event.on("tick", _ => this.#intervalHandler.tick()); |
| 51 | + } |
| 52 | + |
| 53 | + setInterval(callback, interval) { |
| 54 | + return intervalHandler.add( |
| 55 | + new Interval(callback, interval, false) |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + clearInterval(id) { |
| 60 | + intervalHandler.remove(id); |
| 61 | + } |
| 62 | + |
| 63 | + setTimeout(callback, timeout) { |
| 64 | + return intervalHandler.add( |
| 65 | + new Interval(callback, timeout, true) |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + clearTimeout(id) { |
| 70 | + intervalHandler.remove(id); |
| 71 | + } |
| 72 | +})(); |
0 commit comments