You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.6 KiB
JavaScript
64 lines
1.6 KiB
JavaScript
export default class Timer {
|
|
// Recevies a date in the future
|
|
constructor(expiresAt){
|
|
let self = this;
|
|
this.secsLeft = 0;
|
|
this.minsLeft = 0;
|
|
this.hoursLeft= 0;
|
|
this.done = false;
|
|
|
|
// Convert epoch timestamp to date
|
|
if (typeof(expiresAt) === 'number'){
|
|
this.deadline = new Date(expiresAt);
|
|
} else if (expiresAt instanceof Date){
|
|
this.deadline = expiresAt
|
|
} else {
|
|
throw("need instance of Date or unix timestamp")
|
|
}
|
|
|
|
|
|
// Timer done
|
|
if (this.deadline - new Date() <= 0) {
|
|
this.done = true;
|
|
} else {
|
|
this.secsLeft = new Date(this.deadline - new Date()).getSeconds();
|
|
this.minsLeft = new Date(this.deadline - new Date()).getMinutes();
|
|
this.hoursLeft = new Date(this.deadline - new Date()).getHours();
|
|
|
|
// Run ticker
|
|
this.interval = setInterval(function(){
|
|
self.tick()
|
|
}, 1000)
|
|
}
|
|
|
|
}
|
|
|
|
|
|
get secs () {
|
|
return this.secsLeft;
|
|
}
|
|
|
|
get mins(){
|
|
return this.minsLeft;
|
|
}
|
|
|
|
get hours(){
|
|
return this.hoursLeft;
|
|
}
|
|
|
|
tick() {
|
|
if (this.deadline - new Date() <= 0) {
|
|
this.done;
|
|
clearInterval(this.interval);
|
|
return
|
|
}
|
|
this.secsLeft = new Date(this.deadline - new Date()).getSeconds();
|
|
this.minsLeft = new Date(this.deadline - new Date()).getMinutes();
|
|
this.hoursLeft = new Date(this.deadline - new Date()).getHours();
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|