Created
July 30, 2018 15:50
-
-
Save johnstew/77df02d756166fb30869e878daacaa1e to your computer and use it in GitHub Desktop.
timer timer timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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