0

How do I make my objects property available within the callback?

//entrypoint.js
var DeviceManager = require('./class')
DM = new DeviceManager()

DM.start();

var t = setInterval(function() {
  console.log("Module.isLoaded = " + DM.isLoaded);
}, 500);
setTimeout(function() {
  console.log("Stopping");
  clearInterval(t);
  DM.stop();
}, 10000);


//class.js
module.exports = class DeviceManager {
    constructor(){
        this.isLoaded = false;
        this._timer= null;
    }

    start(){

        console.log('starting timer')
        this._timer = setInterval( function() {
            console.log('timer callback')
            this.isLoaded = !this.isLoaded;
        },1000)

    }

    stop() {
        console.log('stopping timer')
        clearInterval(this._timer)
    }
}

Basically this line doesnt work, because it doesnt have access to the correct this I assume.

this.isLoaded = !this.isLoaded

Also, since im all around pretty new at this, any feedback/corrections are very welcome.

jrich523
  • 598
  • 1
  • 5
  • 19

1 Answers1

-1

Try using an arrow function for your setInterval while it's in the class.

An arrow function expression has a shorter syntax than a function expression and does not have its own this

start() {
    this._timer = setInterval( () => {
        this.isLoaded = !this.isLoaded;
    }, 1000)
}
Meghan
  • 1,215
  • 11
  • 17