1

I'm having a javascript function which I have set an interval to execute every 30 seconds. This is my code:

function ping() {
    // code ...
}

ping(); // call function when page loads for first time

// call function every 30 seconds
window.setInterval(function(){
    ping();
}, 30000);

What I'd like to do is to delay the first call (right when the page loads for first time) for 5 seconds and then the function should execute again every 30 secs.

I have tried the setTimeout, but doesn't seem to work, it executes imidiatelly any ideas what I'm doing wrong ?

setTimeout(ping(), 5000); // delay first call for 5 secs

// call function every 30 seconds
    window.setInterval(function(){
        ping();
    }, 30000);
ltdev
  • 4,037
  • 20
  • 69
  • 129

2 Answers2

2

You are calling it immediately on setTimeout(ping(), 5000);. You are setting the result of ping() as the timeout function. If you want ping to be called by the timeout, then either do setTimeout(ping, 5000); or wrap it in a closure, like you did the second time.

Jessidhia
  • 514
  • 4
  • 7
2

I guess you are not waiting until timeout to declare the interval function.

There is a few different ways to do that, so let me suggest one:

function ping() {
    // code ...
}

setTimeout(function () {

    ping(); // call function when page loads for first time

    // call function every 30 seconds
    window.setInterval(function(){
        ping();
    }, 30000);
}, 5000);
lenilsondc
  • 9,590
  • 2
  • 25
  • 40