Home > Software design >  Variable inside object wont change publicly
Variable inside object wont change publicly

Time:04-07

This is probably a really dumb question, I hardly know anything about javascript. When I change a variable of an object inside inside one of the class functions it wont change. "I really can't explain things well.." In this case when I try to "Turn Off" this class, this.Status only = Off in the scope of the Stop function.

Note: I'm using Node.js

Code

module.exports = class Sniper {

    constructor() {
        this.Status = 'Off'
    }

    async start() {
        this.Status = 'On'

        while (this.Status == 'On') {
            console.log(this.Status)
        }

    }

    stop() {
        //When I try to change this value, it only changes in this scope, so the while loop in the start function keeps running
        this.Status = 'Off'
        console.log(this.Status)
    }

}

How do I fix this?

CodePudding user response:

You created an infinite loop. If you mark a function as async it will be still synchronous, but you can start and await Promises in it.

This logic won't work, not really sure what do you want exactly, but you cannot stop a synchronous infinite while loop from outside of its scope.

The closest what I can imagine is something like this:

 class Sniper {

    constructor() {
        this.Status = 'Off'
    }

    async start() {
        this.Status = 'On'

        while (this.Status === 'On') {
// Lets just give a bit of time for the engine to run other code
            await new Promise(resolve=>setTimeout(resolve,10));
            console.log(this.Status)
        }

    }

    stop() {
        //When I try to change this value, it only changes in this scope, so the while loop in the start function keeps running
        this.Status = 'Off'
        console.log(this.Status)
    }

}

const sniper = new Sniper();

sniper.start();

setTimeout(()=>{
 sniper.stop();
},1000);

This will start your loop and you can stop it whenever you want. But as I said, I am not sure what do you want to achieve

CodePudding user response:

If I can understand, you are looking for setInterval here. You can start and stop that using intervalId. Better than using while loop and blocking the only execution thread.

class Sniper {
  constructor() {
    this.Status = "Off";
    this.intervalId = null;
  }

  start() {
    this.Status = "On";

    this.intervalId = setInterval(() => {
      console.log(this.Status);
    }, 1000);
  }

  stop() {
    console.log("Turning off!");
    this.Status = "Off";
    clearInterval(this.intervalId);
  }
}

const foo = new Sniper();
foo.start();

setTimeout(() => {
  foo.stop();
}, 5000);

This will output:

On
On
On
On
Turning off!

Hope this helps..

Happy Coding...

Happy Learning...

  • Related