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:

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

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

hitCount

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!