Skip to content

Instantly share code, notes, and snippets.

@negarjf
Last active November 3, 2019 06:24
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 negarjf/17d76193b9062f199d4494976c567030 to your computer and use it in GitHub Desktop.
Save negarjf/17d76193b9062f199d4494976c567030 to your computer and use it in GitHub Desktop.
Timer for count-down and count-up
/**
* 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;
}
}
@sghgh1996
Copy link

What is duration used for?

@mrastiak
Copy link

mrastiak commented Nov 2, 2019

 reset () {
        this.stop();
        this.currentTime = this.freshCurrentTime;
        this.id = null;
    }

I think it's better to move this.id = null to stop method

@marjandejyab
Copy link

marjandejyab commented Nov 2, 2019

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