Posted by & filed under Web Development.

I had a need to use window.setInterval(code, delay) to a call a method on a JavaScript object every few seconds to rotate some content. However, I found that once setInterval called the code in the callback ‘this’ referenced ‘window’. However, I needed ‘this’ to reference the object that was called by setInterval.

ContentTabs = {
  init: function () {
    setInterval(this.rotate, 5000);
  },
  rotate: function (){
    // this === window
  }
}

After some research I found I was having a closure issue. The solution was to use a ‘self’ variable whose scope is within the closure of the object and wrap the callback code, so it referenced the ‘self’ variable.

ContentTabs = {
  init: function () {
    var self = this;
    setInterval(function() {
       self.rotate();
    }, 5000);
  },
  rotate: function (){
    // this === ContentTabs
  }
}

3 Responses to “JavaScript: Using setInterval Within an Object”

Leave a Reply

  • (will not be published)