Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
983 B
1
Indexable
Never
import { gsap } from "gsap";

export class Ticker {
  constructor() {
    this.rafId = null;

    this.gsapTicker = gsap.ticker;

    /** @type {{fn: Function, priority: Number}[]} */
    this.updateFns = [];
  }

  update = (time, deltaTime, _frame) => {
    this.updateFns.forEach((u) => u.fn({ et: time, dt: deltaTime / 1000 }));
  };

  /**
   * @param {Function} fn
   * @param {undefined|Number} priority
   */
  add(fn, priority = 0) {
    const listener = { fn, priority };

    this.updateFns.push(listener);
    this.updateFns.sort((a, b) => a.priority - b.priority);
  }

  remove(fn) {
    this.updateFns.splice(
      this.updateFns.findIndex((u) => u.fn === fn),
      1
    );
  }

  start() {
    this.stop();
    this.gsapTicker.add(this.update);
  }

  stop() {
    this.gsapTicker.remove(this.update);
  }
}

/**
 * @type {Ticker}
 */
let ticker = null;

export const getDefaultTicker = () => {
  if (!ticker) {
    ticker = new Ticker();
  }

  return ticker;
};