Treat the "stack" as a proper FIFO queue.

The index can't be relied upon because the code is running asynchronously.
Before it gets to the next iteration of `next`, the index will have been
reset, and instead of getting an index greater than the length of all the layers,
you start again from the beginning.

This fix implements this properly using a simple FIFO queue (a stack is LIFO).