Reputation: 5910
I'm currently facing a little Problem in AS3. What I want to achieve is to fade images in a for loop. The problem is that the loop is not waiting for the setInterval function to be finished.
for(var i in imageClips){
setInterval(function(){
fade(imageClips[i]);
}, 6000);
}
The behavior is clear once the setInterval function is called the loop just goes on. My question now is, is there a way to make the loop wait to be done with the things happening in the setInterval function?
Thanks in advance, Thomas
Upvotes: 2
Views: 1384
Reputation: 2945
You could use events instead of waiting for the animation to end. Dispatch a complete event at the end of each animation (for instance on the last frame of a MovieClip):
dispatchEvent(new Event(Event.COMPLETE));
Then add listeners to each animation:
var index:int = -1;
function fadeNext(event:Event = null):void {
index += 1;
if (index < imageClips.length) fade(imageClips[index]);
}
for (var i in imageClips) {
imageClips[i].addEventListener(Event.COMPLETE, fadeNext, false, 0, true);
}
fadeNext();
This way you can change the duration of your animations without the need to synchronize any timeouts.
Upvotes: 0
Reputation: 12431
You'll make your life a whole lot easier if you use a library such as Greensocks' TweenMax for your tweens. It's pretty much the standard for programmatic animation in Flash and provides a staggering number of features including the ability to set a delay on a tween.
Using TweenMax, your code would look something like this:
var delay:int = 6; // delay between fades in seconds
var duration:int = 1; // duration of fade in seconds
for (var i in imageClips)
{
TweenMax.to(imageClips[i], duration, { alpha: 0, delay: i * delay });
}
Upvotes: 1
Reputation: 12420
setInterval
does not delay the loop execution. You can do this:
function fadeImages(imageClips) {
// Create a clone
var imageStack:Array = imageClips.concat();
// Create the callback that will fade all images
var doFade:Function = function() {
if (imageStack.length > 0) {
fade(imageStack.shift());
setInterval(doFade, 6000);
}
}
// Start fading images
doFade();
}
// Fade specified images
fadeImages(imageClips);
If you want to do the fade again, just again the function.
Edit: Wrapped the snippet with a function.
Upvotes: 1