I'm new to JavaScript and I made a simple stopwatch constructor:
function Stopwatch() {
var started = false;
var elapsed;
var start;
d = new Date();
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = d.getTime();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = d.getTime() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(function () {
sw.stop();
console.log(sw.duration());
}, 500);
The logic of the errors works fine, but whenever I call sw.duration(), it always returns zero, and I'm not sure why that is since I'm using var instead of let. Please let me know.