Zack Lovatt | 2d Technical Director

I focus on toolkitting, building custom studio pipelines, expression rigging projects, and creating data-driven animation workflows.

Mail GitHub LinkedIn Skype Vimeo
February 10, 2012

For / While Loops

Posted In: expressions

In class yesterday, one of my students asked about using for / while loops in expressions. As this isn’t something I’ve had to use before, I spent the evening playing around with it.

The main concern is that AE evaluates the entire expression at every frame– there’s no persistence. So any for or while loop will run through in its entirety per frame. If you tried, say, to execute some code while the time is less than 1 second:

while (time < 1){
    // code

You'd find AE caught in an infinite loop-- on the first frame of your comp, the time will ALWAYS be less than 1 second in-- and so it'll time out. From my poking about online, the majority of uses seem to be accumulating data from prior frames.

I've created a mockup of how this works. It counts (and displays) the number of frames a layer is spent above [note: I mean above visually, not greater-than or less-than] a certain y-value. While not the most practical thing around, it should give you a good sense of how to use it.

Here's the code:

L = thisComp.layer("STAR POWER");
curFrame = 0;
hitCount = 0;

while (curFrame <= timeToFrames(time)){
    if (L.transform.position.valueAtTime(framesToTime(curFrame))[1] <= 300){


Let's break it down.

First, we establish the target layer ("STAR POWER"), and we create a variable for the hit count (the number of times the layer goes above 300; hitCount), and another for the iterations of the loop (curFrame).

We then create the while loop. It keeps incrementing the counter until it's at the same frame the comp is currently on– that's how it runs.

Inside that loop, it looks at the the position of the target layer at all previous frames, and if the y-value is above 300, it increments the hit counter and displays that.

If you were so inclined, you could rewrite the same loop as either a for loop or a do while loop. Below you'll find a link to download an AEP with comps containing all three for the price of none!

1 Comment

Would you like to share your thoughts?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.