javascript / intermediate
Snippet
Infinite Sequences with Generators
Generators are special functions that can be paused and resumed. Using a 'while (true)' loop inside a generator doesn't freeze the browser because the 'yield' keyword pauses execution until the next value is requested.
snippet.js
1
2
3
4
5
6
7
8
9
10
function* idGenerator() {let id = 1;while (true) {yield `ID-${id++}`;}}const gen = idGenerator();console.log(gen.next().value); // ID-1console.log(gen.next().value); // ID-2
Breakdown
1
function* idGenerator() {
The asterisk (*) defines this as a generator function.
2
yield `ID-${id++}`;
Pauses execution and returns the current ID string to the caller.
3
const gen = idGenerator();
Invoking the generator returns an iterator object, but doesn't run the code yet.
4
gen.next().value
Resumes the generator until the next yield and retrieves the value.