summaryrefslogtreecommitdiff
path: root/timers.ts
blob: ed84c00e9df9d77510b13fe3e7ab1767dc3f66cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { _global } from "./util";
import { sendMsgFromObject } from "./os";

let nextTimerId = 1;

// tslint:disable-next-line:no-any
type TimerCallback = (...args: any[]) => void;

interface Timer {
  id: number;
  cb: TimerCallback;
  interval: boolean;
  duration: number; // milliseconds
}

const timers = new Map<number, Timer>();

export function setTimeout(cb: TimerCallback, duration: number): number {
  const timer = {
    id: nextTimerId++,
    interval: false,
    duration,
    cb
  };
  timers.set(timer.id, timer);
  sendMsgFromObject({
    timerStart: {
      id: timer.id,
      interval: false,
      duration
    }
  });
  return timer.id;
}
_global["setTimeout"] = setTimeout;

export function timerReady(id: number, done: boolean): void {
  const timer = timers.get(id);
  timer.cb();
  if (done) {
    timers.delete(id);
  }
}