2018-05-21 22:07:40 -04:00
|
|
|
import { main as pb } from "./msg.pb";
|
|
|
|
import * as dispatch from "./dispatch";
|
2018-05-18 11:49:28 -04:00
|
|
|
|
|
|
|
let nextTimerId = 1;
|
|
|
|
|
|
|
|
// tslint:disable-next-line:no-any
|
2018-05-23 14:53:41 -04:00
|
|
|
export type TimerCallback = (...args: any[]) => void;
|
2018-05-18 11:49:28 -04:00
|
|
|
|
|
|
|
interface Timer {
|
|
|
|
id: number;
|
|
|
|
cb: TimerCallback;
|
|
|
|
interval: boolean;
|
2018-05-23 14:53:41 -04:00
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
args: any[];
|
2018-05-18 11:49:28 -04:00
|
|
|
duration: number; // milliseconds
|
|
|
|
}
|
|
|
|
|
|
|
|
const timers = new Map<number, Timer>();
|
|
|
|
|
2018-05-21 22:07:40 -04:00
|
|
|
export function initTimers() {
|
|
|
|
dispatch.sub("timers", onMessage);
|
|
|
|
}
|
|
|
|
|
|
|
|
function onMessage(payload: Uint8Array) {
|
|
|
|
const msg = pb.Msg.decode(payload);
|
|
|
|
const { id, done } = msg.timerReady;
|
|
|
|
const timer = timers.get(id);
|
2018-05-23 14:53:41 -04:00
|
|
|
if (!timer) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
timer.cb(...timer.args);
|
2018-05-21 22:07:40 -04:00
|
|
|
if (done) {
|
|
|
|
timers.delete(id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-23 14:53:41 -04:00
|
|
|
export function setTimeout(
|
|
|
|
cb: TimerCallback,
|
|
|
|
duration: number,
|
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
...args: any[]
|
|
|
|
): number {
|
2018-05-18 11:49:28 -04:00
|
|
|
const timer = {
|
|
|
|
id: nextTimerId++,
|
|
|
|
interval: false,
|
|
|
|
duration,
|
2018-05-23 14:53:41 -04:00
|
|
|
args,
|
2018-05-18 11:49:28 -04:00
|
|
|
cb
|
|
|
|
};
|
|
|
|
timers.set(timer.id, timer);
|
2018-05-23 11:31:53 -04:00
|
|
|
dispatch.sendMsg("timers", {
|
2018-05-18 11:49:28 -04:00
|
|
|
timerStart: {
|
|
|
|
id: timer.id,
|
|
|
|
interval: false,
|
|
|
|
duration
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return timer.id;
|
|
|
|
}
|
2018-05-23 14:53:41 -04:00
|
|
|
|
|
|
|
// TODO DRY with setTimeout
|
|
|
|
export function setInterval(
|
|
|
|
cb: TimerCallback,
|
|
|
|
repeat: number,
|
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
...args: any[]
|
|
|
|
): number {
|
|
|
|
const timer = {
|
|
|
|
id: nextTimerId++,
|
|
|
|
interval: true,
|
|
|
|
duration: repeat,
|
|
|
|
args,
|
|
|
|
cb
|
|
|
|
};
|
|
|
|
timers.set(timer.id, timer);
|
|
|
|
dispatch.sendMsg("timers", {
|
|
|
|
timerStart: {
|
|
|
|
id: timer.id,
|
|
|
|
interval: true,
|
|
|
|
duration: repeat
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return timer.id;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function clearTimer(id: number) {
|
|
|
|
dispatch.sendMsg("timers", {
|
|
|
|
timerClear: { id }
|
|
|
|
});
|
|
|
|
}
|