I have narrowed down the problem of my code to one line, which is where I declare the variables. This is the working code:
function Stopwatch() {
let active = false;
let duration = 0;
let startTime = 0;
let endTime = 0;
this.start = function () {
if (active) {
throw new Error('Stopwatch has already started');
}
startTime = new Date();
active = true;
};
this.stop = function () {
if (!active) {
throw new Error('Stopwatch is not started')
}
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
duration += seconds;
active = false;
};
this.reset = function () {
clearInterval(timer);
active = false;
duration = 0;
};
Object.defineProperty(this, 'duration', {
get: function () { return duration; }
});
}
const sw = new Stopwatch();
and this is the code that’s not working:
function Stopwatch() {
let active = false;
let duration, startTime, endTime = 0;
this.start = function () {
if (active) {
throw new Error('Stopwatch has already started');
}
startTime = new Date();
active = true;
};
this.stop = function () {
if (!active) {
throw new Error('Stopwatch is not started')
}
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
duration += seconds;
active = false;
};
this.reset = function () {
clearInterval(timer);
active = false;
duration = 0;
};
Object.defineProperty(this, 'duration', {
get: function () { return duration; }
});
}
const sw = new Stopwatch();
The only difference is how I declare the variables, if I do it on one line, it fails, but declare them on one line separately it works. What is happening?
Thanks