Juicy
Juicy

Reputation: 12520

setTimeout is instant in function called on load

I can't understand why the switchImage() function gets called immediately after the page is loading instead of waiting three seconds.

function initSlideshow() {

   //Do some initialization stuff first

   window.setTimeout(switchImage(),3000);
}

function switchImage() {
   alert();
}

window.onload = initSlideshow;

You can see the actual page in action here

Upvotes: 0

Views: 108

Answers (2)

epascarello
epascarello

Reputation: 207511

You are calling it since you have the ()

window.setTimeout(switchImage(),3000);
                            ^^^

This is how you assign it, you drop the ()

window.setTimeout(switchImage,3000);

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

The () immediately invoke the function, omit () to pass the function along rather than call it immediately.

window.setTimeout(switchImage,3000);

Upvotes: 1

Related Questions