Last active
February 20, 2019 00:38
-
-
Save lewdev/bc4d1fc963205f28f687763cac294d82 to your computer and use it in GitHub Desktop.
Simple timer object for calculating run-time with option to display the time in seconds.
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
/** | |
Example JS: | |
const timer = new Timer(); | |
timer.start(); | |
timer.stop(); | |
Example HTML: | |
<span id="timerDisplay"><!-- not required --></span> | |
<button onclick="timer.start();">start</button> | |
<button onclick="timer.stop();">stop</button | |
*/ | |
function Timer() { | |
this.timerInterval = null; | |
this.startTime = 0; | |
this.timerDisplay = document.getElementById("timerDisplay"); | |
this.start = function() { | |
clearInterval(this.timerInterval); | |
this.startTime = (new Date()).getTime(); | |
console.log("START TIME: " + (new Date()).toLocaleTimeString()); | |
if (this.timerDisplay) { | |
this.timerDisplay.innerHTML = 0; | |
this.timerInterval = setInterval(() => { | |
const seconds = ((new Date()).getTime() - thisRef.startTime) / 1000; | |
if (thisRef.timerDisplay) { | |
thisRef.timerDisplay.innerHTML = seconds + " seconds";// Math.round(seconds * 100) / 100; | |
} | |
}, 10); | |
} | |
const thisRef = this; | |
} | |
this.stop = function() { | |
clearInterval(this.timerInterval); | |
const timestamp = (new Date()).toLocaleTimeString(); | |
const seconds = (((new Date()).getTime() - this.startTime) / 1000); | |
console.log("STOP TIME: " + timestamp + ", time=" + seconds + " seconds"); | |
if (this.timerDisplay) { | |
this.timerDisplay.innerHTML = seconds + " seconds"; | |
} | |
return seconds; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment