Generators (ES6) Sample

Available in Chrome 39+

Generators are special functions which produce iterators when constructed. The yield statement within a generator suspends execution and returns control back to the calling function, and normally also returns a value. Subsequent iterations will reuse the previous state and continue execution of the generator code where it last left off.

This two-part example relies on a generator function which yields the words in the first sentence of Lorem ipsum..., one at a time.

The first part uses an iterator that terminates after yielding five words, and the words can optionally be yielded in uppercase.

The second part uses an iterator that will continue yielding words infinitely, looping around to the beginning after the last word in the "Lorem ipsum..." sequence is yielded. Since infinite loops are no fun, we explicitly break out of the iteration once enough words have been yielded to take up 300px of vertical space on the page.

Five Words

The buttons will add words until the iterator runs out:

300px Worth of Words

This will add enough words to use up 300px of vertical space: