3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-05-23 17:45:03 +00:00
zeppelin/backend/src/utils/timers.ts
2021-09-20 21:39:20 +00:00

40 lines
930 B
TypeScript

import { Snowflake } from "discord-api-types";
type TimerCallback = (key: string, expiry: number) => void;
type TimerOptions = {
key: Snowflake;
guildId?: Snowflake;
expiry: number;
plugin?: string;
callback: TimerCallback;
};
export class ExpiringTimer {
done: boolean = false;
options: TimerOptions;
timeout?: NodeJS.Timeout;
data?: any; // idk how to make this take generic <T> typings data
isValid() {
return !this.done;
}
private execute() {
if (!this.isValid()) return;
this.options.callback(this.options.key, this.options.expiry);
this.done = true;
}
init() {
if (this.timeout) this.clear();
this.timeout = setTimeout(() => this.execute(), this.options.expiry);
}
clear() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = undefined;
}
}
constructor(options: TimerOptions) {
this.options = options;
this.init();
}
}