First let’s remove the pictures we don’t need anymore, we could add this at the end of our get_next_picture function:

while(numChildren>2){ removeChildAt(0); }

Only problem is if you were to add other objects to the slide show like textfields for example this code would break, so we need another approach. As always there’s many ways to go about this, here is what I chose to do. Instead of adding the pictures to the stage, I will add them to a main Sprite and then use the preceding code for the main Sprite instead. So let’s modify our code and add a main Sprite:

private var picture_holder:Sprite = new Sprite(); //new variable
addChild(picture_holder);//in the constructor
picture_holder.addChild(picture_loader);//in the get_next_picture function
while(picture_holder.numChildren>2){//at the end of the get_next_picture function
picture_holder.removeChildAt(0);
}

The loader objects we remove will be garbage collected since they lost any reference in the code. Now let’s make our timer more accurate. We can just get the current time and use our timer to check when the targeted time occurs and then trigger our function, that way we’ll get a more accurate timing.

private var current_time:Number;//create a new variable to hold the current time
display_timer = new Timer(50);
//we place this inside our get_next_picture function
current_time = getTimer();
//we place this inside our get_next_picture function
display_timer.addEventListener(TimerEvent.TIMER, check_target_time);
//we place this inside our get_next_picture function
display_timer.start();
//we place this inside our get_next_picture function

and here is our new function:

private function check_target_time(e:TimerEvent):void{
if(getTimer()>current_time+(display_time*1000)){
//if the actual time passes the initial time + the target time
//(+5 seconds) then it's time to get a new picture
display_timer.removeEventListener(TimerEvent.TIMER, check_target_time);
get_next_picture(); } }

Now we got an accuracy of more or less 50 milliseconds. You can get an even better accuracy by reducing the number passed to the timer (new Timer(50)). Now we need to change our code logic so that as soon as we display a picture, we start to load the next one so when the time comes to display it we can just do so. Let's see that in the next page.