Created
September 13, 2019 07:25
-
-
Save novonimo/8129d55b7f6404fdb79e483f64d3dab2 to your computer and use it in GitHub Desktop.
simple OOP exercise, stopwatch that count time between start and stop
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
/** | |
* Stopwatch onject will used for count time between start and stop time | |
* there are thre method on it: start, stop, reset | |
* and there are one property "duration" | |
* Implement constructor function for create object | |
*/ | |
function Stopwatch () { | |
let duration = 0; | |
let intervalId = null; | |
let isRunning = false | |
this.start = function () { | |
if (isRunning) { | |
throw new Error("Stopwach has already started"); | |
} else { | |
isRunning = true; | |
intervalId = setInterval(()=> duration++, 1000); | |
} | |
} | |
this.stop = function () { | |
if (isRunning) { | |
clearInterval(intervalId) | |
isRunning = false | |
} else { | |
throw new Error("Stopwach is not started"); | |
} | |
} | |
this.reset = function () { | |
duration = 0; | |
} | |
Object.defineProperty(this, "duration", { | |
get: function () {return duration} | |
}) | |
} | |
// const sw = new Stopwatch(); | |
// sw.start() | |
// sw.stop() | |
// sw.reset() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment