Skip to content

Instantly share code, notes, and snippets.

@johnstew
Created July 30, 2018 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnstew/77df02d756166fb30869e878daacaa1e to your computer and use it in GitHub Desktop.
Save johnstew/77df02d756166fb30869e878daacaa1e to your computer and use it in GitHub Desktop.
timer timer timer
class Timer {
constructor(duration) {
const initDuration = (duration || 1) * 60;
this.initDuration = initDuration;
this.duration = initDuration;
this.intervalId = -1;
this.interval = 1000;
this.displayDuration = `${duration}:00`;
}
run() {
this.intervalId = window.setInterval(() => {
let minutes = parseInt(this.duration / 60, 10);
let seconds = parseInt(this.duration % 60, 10);
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
this.displayDuration = `${minutes}:${seconds}`;
console.log(this.displayDuration);
this.duration--;
if (this.duration < 0) {
window.clearInterval(this.intervalId);
}
}, this.interval);
}
cancel() {
window.clearInterval(this.intervalId);
}
reset() {
this.duration = this.initDuration;
this.intervalId = -1;
this.displayDuration = `${this.duration}:00`;
}
}
const t = new Timer(1);
t.run();
setTimeout(() => t.cancel(), 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment