The loop cannot be extracted out of the anonymous function, otherwise the block will not have access to the `l` (counter) variable.
Maybe the variable could be renamed to `remaining`. And maybe a couple of comments more.

The logic is similar to what jquery does in queue.js though