deadhead-space-freight-tycoon/apps/web/src/map/ticker.ts

21 lines
713 B
TypeScript

/** The part of a PixiJS `Ticker` the map's lifecycle needs (a fake in tests). */
export interface Startable {
start(): void;
stop(): void;
}
/**
* Runs `ticker` only while the page is visible (Step 10C.9): stops it when the
* page is hidden and starts it again when it returns. The returned cleanup (for
* unmounting the Map) stops it and removes the listener.
*/
export function runWhileVisible(ticker: Startable, doc: Document = document): () => void {
const sync = () => (doc.visibilityState === "hidden" ? ticker.stop() : ticker.start());
doc.addEventListener("visibilitychange", sync);
sync();
return () => {
doc.removeEventListener("visibilitychange", sync);
ticker.stop();
};
}