I’m missing some fundamental understanding of javascript function flow control…
I’ve created a jquery slideshow. The show is broken down into logical sections, each section is controlled by a function (makes it easy to add sections later)…
function myslideshow() {
section1();
section2();
section3();
}
Each section has multiple functions composed of jquery statements, animations, timed stuff…so maybe..
function section1() {
firstPart();
setTimeout('secondPart()',5000);
setTimeout('thirdPart()',6000);
}
Now here’s my issue… I want to define the functions “firstPart(), secondPart(), thirdPart()” inside of section1(). I want to do this for various reasons:
- Each section may logically have their own “parts”
- Portability of the section
So I would like to keep the section and all of its respective parts inside of the section.
I can’t seem to get it to work… when I define “parts” inside of the section all of the functions are ran at the same time.
so ideally what I’d like to have is:
function section1() {
firstPart();
setTimeout('secondPart()',5000);
setTimeout('thirdPart()',6000);
function firstpart(){
//some code here
}
function secondPart(){
//some code here
}
function thirdPart(){
//some code here
}
}
But again that doesn’t work out properly; actually it works properly I’m just not implementing it properly! Not sure if I need to leverage function callbacks (not even sure how to set that up in a “scalable manner”).
Another area for improvement: setTimeouts are used to ensure the secondPart runs after the firstPart… wondering if there are better ways to “wait” on the previous function (with jquery animations) to complete.
I appreciate any direction that you can offer. Thanks!
You’re calling “setTimeout()” incorrectly:
That will pass a reference to your local function. When you pass a string, the runtime system will evaluate it when the timer goes off, in the global context. Thus, it won’t find your local function.
As to your last question, most (if not all) jQuery animation routines allow a function to be passed as the last argument. The function is run after the animation completes. Again, in such cases, you should pass a reference to your function and not a string containing a function call expression. (I doubt that would work with jQuery anyway.)