Self invoking function via setTimeout within object

algi picture algi · Feb 29, 2012 · Viewed 7.9k times · Source

I would like invoke a method of an js object within the very same object method via setTimeout:

var ads = {

  init: function() {
    ads.display_ads();
  },

  display_ads: function() {
     console.log('Displaying Ads');
     setTimeout('ads.display_ads()', 5000);
  }
}

However, I'm getting this error message:

ads is not defined

setTimeout('ads.display_ads()', 2000);

What am I missing here? How would i alter the string within the setTimeout function?

Thanks for your help!

Edit: I use firefox on mac.

Answer

jabclab picture jabclab · Feb 29, 2012

Just change it to ads.display_ads, note that this is not a String. i.e.

var ads = {
    init: function() {
        ads.display_ads();
    },
    display_ads: function() {
        console.log('Displaying Ads');
        setTimeout(ads.display_ads, 5000);
    }
}

As @FelixKling points out in his comment below, be careful about what this refers to in ads.display_ads. If ads.display_ads is called via ads.init() or ads.display_ads() this will be the ads Object. However, if called via setTimeout this will be window.

If the context is important though, you can pass an anonymous function to setTimeout, which in turn calls ads.display_ads():

setTimeout(function() {
    ads.display_ads();
}, 5000);

or

var self = this;
setTimeout(function() {
    self.display_ads();
}, 5000);