1

I have the below script.

function slideShow1(){
    document.getElementById('dynimg').src="Other/noctis.jpg";
    var timer1 = setTimeout(slideShow2(),5000);
}

function slideShow2(){
    document.getElementById('dynimg').src="Other/retriever.jpg";
    var timer2 = setTimeout(slideShow3(),5000);
}

function slideShow3(){
    document.getElementById('dynimg').src="Other/miningop2.jpg";
    var timer3 = setTimeout(slideShow1(),5000);
}

It's crude, I know... And it's also not working. The idea is for each function to trigger the next after a given period and therefore creating a slideshow where and img is changed repeatedly. I am trying to use body onload="slideShow1()"

1 Answer 1

6

Those parentheses are causing your function to be executed immediately.

setTimeout(slideShow2(), 5000);

As such, you think you're passing your function to setTimeout but you're actually executing your function and passing its return value (undefined in this case).

So, your function gets called immediately and setTimout has nothing to execute five seconds later.

Just remove the parentheses:

function slideShow1(){
    document.getElementById('dynimg').src = "Other/noctis.jpg";
    setTimeout(slideShow2, 5000);
}

function slideShow2(){
    document.getElementById('dynimg').src = "Other/retriever.jpg";
    setTimeout(slideShow3, 5000);
}

function slideShow3(){
    document.getElementById('dynimg').src = "Other/miningop2.jpg";
    setTimeout(slideShow1, 5000);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Another way to say it: you're passing "the result of executing the function" rather than passing "a reference to a function that will get executed later".
So the object returned by the function will be the one that would get called the call() method on.
Does this mean that I can't parse a function with an argument into setTimeout?
@canon - Sorry, I probably wasn't clear. Lets say I want my setImgSrc(newSrc){} function to be called by a setTimeout function.. does that mean I can't because setImgSrc requires an arguement?
@canon Please don't suggest that. It's non-standard and doesn't work in IE. You even provided the link to the MDN docs that say this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.