Skip to content

Instantly share code, notes, and snippets.

@dbugshe2
Created December 11, 2023 12:06
Show Gist options
  • Save dbugshe2/3a42e7e3080d257cbba736a8a80bbd1b to your computer and use it in GitHub Desktop.
Save dbugshe2/3a42e7e3080d257cbba736a8a80bbd1b to your computer and use it in GitHub Desktop.
Timer class in js
class Timer {
constructor(duration, callback) {
this.duration = duration;
this.callback = callback;
this.remainingTime = duration;
this.timerId = null;
this.paused = false;
}
async start() {
try {
console.log('Countdown started.');
this.timerId = setInterval(() => {
if (!this.paused) {
this.remainingTime -= 1000;
console.log(`${this.remainingTime / 1000}s remaining.`);
if (this.remainingTime <= 0) {
clearInterval(this.timerId);
console.log('Countdown completed.');
this.callback();
}
}
}, 1000);
} catch (error) {
console.error('Error during countdown:', error);
}
}
async pause() {
console.log('Countdown paused.');
this.paused = true;
}
async resume() {
console.log('Countdown resumed.');
this.paused = false;
}
async cancel() {
clearInterval(this.timerId);
console.log('Countdown canceled.');
}
}
// Example usage:
const countdown = new Timer(5000, async () => {
console.log('Simulated async process completed.');
});
countdown.start();
// Pause after 2 seconds
setTimeout(() => countdown.pause(), 2000);
// Resume after 1 second
setTimeout(() => countdown.resume(), 3000);
// Cancel after 4 seconds
setTimeout(() => countdown.cancel(), 4000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment