Skip to content

Instantly share code, notes, and snippets.

@andrearufo
Created September 5, 2022 11:49
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 andrearufo/2b9fd12fc1be582b160421ab18f6c36b to your computer and use it in GitHub Desktop.
Save andrearufo/2b9fd12fc1be582b160421ab18f6c36b to your computer and use it in GitHub Desktop.
Javascript Timer Class
export class Timer {
constructor() {
this.offset = 4692;
this.seconds = 0;
this.interval = null;
this.running = false;
this.history = []
}
start() {
this.history.push({
action: 'start',
date: new Date().toISOString()
});
this.running = true;
const startDate = new Date();
this.interval = setInterval( ()=>{
const currentDate = new Date();
this.seconds = parseInt((currentDate - startDate) / 1000);
}, 1000)
}
stop() {
this.history.push({
action: 'stop',
date: new Date().toISOString()
});
clearInterval(this.interval);
this.offset = this.offset + this.seconds;
this.seconds = 0;
this.running = false;
}s
add(seconds) {
this.history.push({
action: 'add',
value: seconds
});
this.offset = this.offset + seconds
}
elapsed () {
return this.offset + this.seconds;
}
display() {
var date = new Date(null);
date.setSeconds( this.elapsed() );
var result = date.toISOString().substr(11, 8);
return result
}
reset() {
this.history.push({
action: 'reset',
date: new Date().toISOString()
});
clearInterval(this.interval);
this.offset = 0;
this.seconds = 0;
this.running = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment