user2064000
user2064000

Reputation:

Pass "this" into window.setInterval()

I have code that looks like this:

var X = {
  updateAll: function() {
    // ...
  },

  init: function() {
    window.setInterval(function() {
      this.updateAll();
    }, 40000);
  }
}

In X.init(), I want to be able to access updateAll(), but for obvious reasons it does not work as intended.

How can I achieve the required outcome?

Upvotes: 0

Views: 332

Answers (4)

Harry Pehkonen
Harry Pehkonen

Reputation: 3038

You can use the var self = this method as mentioned in other answers, OR you can use the .bind method that functions have:

var X = {
  updateAll: function() {
    // ...
  },

  init: function() {
    window.setInterval(
      this.updateAll.bind(this),
      40000
    );
  }
}

Please note that you don't need all that "function() {...}" in the first argument to setInterval -- it's redundant.

Upvotes: 0

Nicolò
Nicolò

Reputation: 1875

You can bind the function:

init: function() {
    window.setInterval(function() {
        this.updateAll();
    }.bind(this), 40000);
}

Or, if you are using ECMAScript 2015, you can use an arrow function:

init: function() {
    window.setInterval(() => {
        this.updateAll();
    }, 40000);
}

Upvotes: 0

rajesh
rajesh

Reputation: 2523

you can do it this way.

var X = {
  updateAll: function() {
    console.log('updateALL');
  },
  init: function() {
    var self=this;
    window.setTimeout(function() {
      self.updateAll();
    }, 200);
  }
};

Upvotes: 0

tklg
tklg

Reputation: 2642

  init: function() {
    var _self = this;
    window.setInterval(function() {
      _self.updateAll();
    }, 40000);
  }

Upvotes: 3

Related Questions