summaryrefslogtreecommitdiff
path: root/timers.ts
diff options
context:
space:
mode:
authorParsa Ghadimi <me@qti3e.com>2018-05-23 23:23:41 +0430
committerRyan Dahl <ry@tinyclouds.org>2018-05-23 17:07:20 -0400
commitcb222ceb227f5a7f5307085bcbebfa3cdb049598 (patch)
tree312f3a1c46af2c668d68881ea62f56ac27d99b9d /timers.ts
parent3171ba4c3ff4046aaca0d70321f1dfec4c0728bb (diff)
Adds setInterval, clearInterval, clearTimeout.
Diffstat (limited to 'timers.ts')
-rw-r--r--timers.ts48
1 files changed, 45 insertions, 3 deletions
diff --git a/timers.ts b/timers.ts
index f5f039f1c..5407c63b0 100644
--- a/timers.ts
+++ b/timers.ts
@@ -4,12 +4,14 @@ import * as dispatch from "./dispatch";
let nextTimerId = 1;
// tslint:disable-next-line:no-any
-type TimerCallback = (...args: any[]) => void;
+export type TimerCallback = (...args: any[]) => void;
interface Timer {
id: number;
cb: TimerCallback;
interval: boolean;
+ // tslint:disable-next-line:no-any
+ args: any[];
duration: number; // milliseconds
}
@@ -23,17 +25,26 @@ function onMessage(payload: Uint8Array) {
const msg = pb.Msg.decode(payload);
const { id, done } = msg.timerReady;
const timer = timers.get(id);
- timer.cb();
+ if (!timer) {
+ return;
+ }
+ timer.cb(...timer.args);
if (done) {
timers.delete(id);
}
}
-export function setTimeout(cb: TimerCallback, duration: number): number {
+export function setTimeout(
+ cb: TimerCallback,
+ duration: number,
+ // tslint:disable-next-line:no-any
+ ...args: any[]
+): number {
const timer = {
id: nextTimerId++,
interval: false,
duration,
+ args,
cb
};
timers.set(timer.id, timer);
@@ -46,3 +57,34 @@ export function setTimeout(cb: TimerCallback, duration: number): number {
});
return timer.id;
}
+
+// 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 }
+ });
+}