smobx smobx - 2 years ago 140
Javascript Question

Javascript Timeout with delay

i have some problems with my setTimeout and setInterval functions. What i need to do is displaying an ad 2 seconds after the app was launched and then display it every 2 minutes.
Good, untill now i managed to do the first half of the problem (display it after 2 seconds) but i can't figure it out how to delay the timeout with another 2 minutes and execute it in a loop (probably with setInterval).
I tried adding another timeout in this timeout but it delays the first execution.

I would apreciate some help.
Here is my code untill now:

setTimeout(function() {
// this will create a banner on startup
AdMob.createBanner( {
adId: admobid.banner,
overlap: false,
offsetTopBar: false,
bgColor: 'black'
} );

// this will load a full screen ad on startup
adId: admobid.interstitial,
autoShow: true
}, 2000);

Answer Source

If you're trying to call the same code after 2 seconds and then again every 2 minutes, you can do that like this:

function someAdCode() {
    // put the code here that you want to repeat

// start it in 2 seconds
setTimeout(function() {
    // schedule it to repeat every 2 minutes
    setInterval(someAdCode, 2 * 60 * 1000);
}, 2000);

This uses a setTimeout() for the one-time 2 second delay. Then, in that callback, you start the setInterval() to repeat every 2 minutes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download