0

I am new to javascript and was trying to create a stopwatch object as described in a youtube video. Following is the code:

function Stopwatch(){
    let durationVal = 0;
    let startFlag = 0;

    this.start = function(){
            if (startFlag === 0){
                    durationVal = Date.now()
                    startFlag = 1;        
            }
            else{
                    throw new Error('Stopwatch is already running')
            }
    }

    this.stop = function(){
            if(startFlag === 1){
                    durationVal = Date.now() - durationVal
                    startFlag = 0;
            }
            else{
                    throw new Error('Stopwatch is not running')
            }
    }

    this.duration = durationVal;

    this.reset = function(){
            durationVal = 0;
    }

}

When I try to create an object and access its duration property

let sw = new Stopwatch()
sw.start()
sw.stop()
console.log(sw.duration)

It returns a zero. However, when I change my javascript to use a method to get the duration value:

 this.duration = function(){
            return durationVal;
 }

it gives the correct value. Can you explain why?

  • 1
    `duration` gets its value once when it is a field; when the object is created (and `durationVal` is 0). You could use a property getter instead: `get duration() { return durationVal; }` – Heretic Monkey Mar 24 '22 at 22:14
  • Either use `this.duration` or `durationVal` consistently. – Barmar Mar 24 '22 at 22:17
  • If you want to be able to access it as a property, just use `this.duration` everywhere, get rid of `durationVal`. – Barmar Mar 24 '22 at 22:18
  • 1
    Because the statement code `this.duration = durationVal;` only runs once when `new Stopwatch()` executes, whereas the function`function(){ return durationVal; }` runs every time you call it. – leo Mar 24 '22 at 22:33
  • Thank you all :), I understood it now. this.duration is not getting updated as I make changes to durationVal. – Tej Partap Singh Mar 26 '22 at 19:53

0 Answers0