Skip to content

Instantly share code, notes, and snippets.

@FirstVertex
Last active September 25, 2022 14:47
Show Gist options
  • Save FirstVertex/540275a149fec5628399954035ca6b56 to your computer and use it in GitHub Desktop.
Save FirstVertex/540275a149fec5628399954035ca6b56 to your computer and use it in GitHub Desktop.
Lightlimn Roblox Timer module remixed for TypeScript by FirstVertex
import { RunService } from "@rbxts/services";
export class Timer {
constructor(private _duration: number, private _onComplete?: () => void, private _elapsed = 0, autoStart = true) {
if (autoStart) {
spawn(() => this.start());
}
}
private _paused: boolean = true;
private _startTime: number = 0;
private _connection: RBXScriptConnection | undefined = undefined;
start(duration = this._duration) {
if (!this._paused || this._connection) {
return;
}
this._duration = math.max(0, duration);
this._startTime = os.clock() - this._elapsed;
this._paused = false;
this._connection = RunService.Heartbeat.Connect(() => {
this._update()
});
}
stop() {
this._update();
this._paused = true;
if (this._connection) {
this._connection.Disconnect();
this._connection = undefined;
}
}
getPercentComplete(): number {
if (this._duration <= 0 || this._elapsed <= 0) {
return 0;
}
if (this._elapsed >= this._duration) {
return 1;
}
return this._elapsed / this._duration;
}
getRemainingTime(): number {
return math.max(0, this._duration - this._elapsed);
}
private _update() {
if (this._paused) {
return;
}
const stamp = os.clock();
const elapsed = stamp - this._startTime;
if (elapsed >= this._duration) {
this._paused = true;
this._elapsed = this._duration;
if (this._connection) {
this._connection.Disconnect();
this._connection = undefined;
}
if (this._onComplete !== undefined) {
this._onComplete();
}
} else {
this._elapsed = elapsed;
}
}
}
import { Timer } from "shared/timer";
export class MapStateTracker {
constructor(delayInSeconds: number) {
this._timer = new Timer(delayInSeconds, () => this._moveToNextMap());
}
protected _timer: Timer;
getCurrentMapPercentComplete(): number {
return this._timer.getPercentComplete();
}
teardown() {
if (this._timer) {
this._timer.stop();
}
}
protected _moveToNextMap() {
// do work
}
}
@FirstVertex
Copy link
Author

FirstVertex commented Sep 16, 2022

Remix from the original devforum post here
https://devforum.roblox.com/t/oop-timer-module/285360

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment