Last active
November 3, 2019 06:24
-
-
Save negarjf/17d76193b9062f199d4494976c567030 to your computer and use it in GitHub Desktop.
Timer for count-down and count-up
This file contains 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
/** | |
* Timer class for count-down and count-up | |
*/ | |
class Timer { | |
constructor (duration = 0, countDown = true, step = 1) { | |
this.duration = duration; | |
this.countDown = countDown; | |
this.step = step; | |
this.opr = countDown ? -1 : 1; | |
this.currentTime = this.freshCurrentTime; | |
this.id = null; | |
} | |
/** | |
* get fresh current time | |
* @returns {number} | |
*/ | |
get freshCurrentTime () { | |
return this.countDown ? this.duration : 0; | |
} | |
/** | |
* tick timer for one step | |
*/ | |
tick () { | |
this.currentTime = this.currentTime + this.opr * this.step; | |
} | |
/** | |
* start timer count | |
*/ | |
start () { | |
this.id = setInterval(() => { | |
if ( | |
(this.countDown && this.currentTime > 0) || | |
(!this.countDown && this.currentTime < this.duration) | |
) { | |
this.tick(); | |
} else { | |
this.stop(); | |
} | |
}, this.step * 1000); | |
this.tick(); | |
} | |
/** | |
* stop timer count | |
*/ | |
stop () { | |
clearInterval(this.id); | |
this.id = null; | |
} | |
/** | |
* reset timer properties | |
*/ | |
reset () { | |
this.stop(); | |
this.currentTime = this.freshCurrentTime; | |
} | |
/** | |
* get current time | |
* @returns {number|*} | |
*/ | |
get second () { | |
return this.currentTime; | |
} | |
} |
if (this.countDown && this.currentTime > 0) {
this.tick();
} else if (!this.countDown && this.currentTime < this.duration) {
this.tick();
} else {
this.stop();
}```
You can combine "if" and "else if" conditions with an "or" operator (||)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it's better to move
this.id = null
tostop
method