Created
September 5, 2022 11:49
-
-
Save andrearufo/2b9fd12fc1be582b160421ab18f6c36b to your computer and use it in GitHub Desktop.
Javascript Timer Class
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
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