Create a Stopwatch
function with start
, stop
, reset
methods and duration
property.
Stopwatch function |
The name of the function. |
---|---|
start method |
It will allow the timer to start. Throw an error message if the someone attempts to call this method more than once. ie("Stopwatch has already started.") |
stop method |
It will allow the timer to stop. Throw an error message if the someone attempts to call this method more than once. ie("Stopwatch is not started.") |
reset method |
Allows you to reset the timer. Duration will become 0. |
duration property |
Shows the duration of the timer. |
function Stopwatch () {
let startTime, endTime, running, duration = 0;
this.start = function () {
if (running)
throw new Error('Stopwatch has already started.');
running = true;
startTime = new Date();
return 'Timer has started.'
};
this.stop = function () {
if (!running)
throw new Error('Stopwatch is not started.');
running = false;
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
duration += seconds;
return 'Timer has stopped.'
};
this.reset = function () {
startTime = null;
endTime = null;
running = false;
duration = 0;
return 'Timer was reset.'
};
Object.defineProperty( this, 'duration', {
get: function () { return duration; }
});
}