1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00
denoland-deno/timers.ts

90 lines
1.8 KiB
TypeScript
Raw Normal View History

2018-05-28 21:50:44 -04:00
// Copyright 2018 Ryan Dahl <ry@tinyclouds.org>
// All rights reserved. MIT License.
2018-05-21 22:07:40 -04:00
import { main as pb } from "./msg.pb";
import * as dispatch from "./dispatch";
2018-05-25 15:36:13 -04:00
import { assert } from "./util";
2018-05-18 11:49:28 -04:00
let nextTimerId = 1;
// tslint:disable-next-line:no-any
export type TimerCallback = (...args: any[]) => void;
2018-05-18 11:49:28 -04:00
interface Timer {
id: number;
cb: TimerCallback;
interval: boolean;
// 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);
2018-05-25 15:36:13 -04:00
assert(msg.command === pb.Msg.Command.TIMER_READY);
const id = msg.timerReadyId;
const done = msg.timerReadyDone;
2018-05-21 22:07:40 -04:00
const timer = timers.get(id);
if (!timer) {
return;
}
timer.cb(...timer.args);
2018-05-21 22:07:40 -04:00
if (done) {
timers.delete(id);
}
}
function setTimer(
cb: TimerCallback,
duration: number,
interval: boolean,
// tslint:disable-next-line:no-any
args: any[]
): number {
2018-05-18 11:49:28 -04:00
const timer = {
id: nextTimerId++,
interval,
2018-05-18 11:49:28 -04:00
duration,
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-25 15:36:13 -04:00
command: pb.Msg.Command.TIMER_START,
timerStartId: timer.id,
timerStartInterval: interval,
2018-05-25 15:36:13 -04:00
timerStartDuration: duration
2018-05-18 11:49:28 -04:00
});
return timer.id;
}
export function setTimeout(
cb: TimerCallback,
duration: number,
// tslint:disable-next-line:no-any
...args: any[]
): number {
return setTimer(cb, duration, false, args);
}
export function setInterval(
cb: TimerCallback,
repeat: number,
// tslint:disable-next-line:no-any
...args: any[]
): number {
2018-05-31 13:55:53 -04:00
return setTimer(cb, repeat, true, args);
}
export function clearTimer(id: number) {
dispatch.sendMsg("timers", {
2018-05-25 15:36:13 -04:00
command: pb.Msg.Command.TIMER_CLEAR,
timerClearId: id
});
}