Skip to content

Instantly share code, notes, and snippets.

@novonimo
Created September 13, 2019 07:25
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 novonimo/8129d55b7f6404fdb79e483f64d3dab2 to your computer and use it in GitHub Desktop.
Save novonimo/8129d55b7f6404fdb79e483f64d3dab2 to your computer and use it in GitHub Desktop.
simple OOP exercise, stopwatch that count time between start and stop
/**
* 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