better-timer
Version:
A promise-based timer that can be paused
55 lines (53 loc) • 1.31 kB
JavaScript
(() => {
// src/modules/Timer.ts
var Timer = class {
constructor(duration, ...callbacks) {
this.duration = duration;
this.callbacks = [];
this.isRunning = false;
this.callbacks.push(...callbacks);
this.startedAt = this.currentTimestamp;
this.timeLeft = this.duration;
this.createTimer(this.duration);
}
execCallbacks() {
this.callbacks.forEach((callback) => {
callback();
});
}
get promise() {
return new Promise((resolve) => {
this.callbacks.push(resolve);
});
}
createTimer(duration) {
if (this.isRunning) {
return;
}
this.timer = setTimeout(() => {
this.execCallbacks();
this.isRunning = false;
}, duration);
this.isRunning = true;
}
pause() {
this.cancel();
const timeElapsed = this.currentTimestamp - this.startedAt;
const timeLeft = this.duration - timeElapsed;
this.timeLeft = timeLeft;
}
resume() {
this.createTimer(this.timeLeft);
}
cancel() {
clearTimeout(this.timer);
this.isRunning = false;
}
get currentTimestamp() {
return window.performance.now();
}
};
// src/bundle.ts
window.Timer = Timer;
})();
//# sourceMappingURL=better-timer.js.map