Iterator

July 6th, 2007

I was working on some javascript for things like fading and animation.  These functions all have a similar structure:

And I wanted to abstract this away to an iterator function so I could do something like:

This would execute the anonymous function repeatedly until it returns false.  Here’s what I came up with:

It works by creating an anonymous function that sets a callback to itself.  Since there’s no way to call anonymous functions directly, it is called with itself as a parameter.

It also allows specifying an “end” function that is called after the iteration finishes.  This end function can set up an iterator itself.  So, to move an element right, then fade it out, you could do:

This came up when I was working on LAMEO.  I was designing a AJAX response handler and wanted a way to easily do UI effects and chain events so they happen back-to-back.  I’m not sure if I’ll end up using it, but it was fun to make.

Update

Here’s a slightly improved version:

This way, no parameter is passed to the function created. Other than that it’s the same.

Leave a Reply

Name

Website

Comment