const fragment = document.createDocumentFragment()
const append = () => fragment.append(document.createElement('div'))
const observer = new MutationObserver()
observer.observe(frag, {
childList: true
})
append()
append()
setTimeout(append, 1000)
setTimeout(() => observer.disconnect(), 3000)
setTimeout(append, 4000)
for await (const record of observer) {
console.log(record)
}
console.log('end')
Last active
September 28, 2021 13:22
-
-
Save Lcfvs/125738d32d01892f62bbef2f575e6fa7 to your computer and use it in GitHub Desktop.
A MutationObserver providing an iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class MutationObserver extends globalThis.MutationObserver { | |
#consumed = false | |
#promises = [] | |
#resolve = null | |
#enqueue = record => { | |
if (this.#resolve) { | |
this.#resolve(record) | |
this.#next() | |
} | |
} | |
#next = () => this.#promises.push(new Promise(this.#wait)) | |
#wait = resolve => this.#resolve = resolve | |
constructor () { | |
super(records => { | |
for (const record of records) { | |
this.#enqueue(record) | |
} | |
}) | |
this.#next() | |
} | |
disconnect () { | |
this.#resolve() | |
this.#resolve = null | |
super.disconnect() | |
} | |
async* getIterator () { | |
if (this.#consumed) { | |
throw new Error('Unable to create an additional iterator') | |
} | |
this.#consumed = true | |
while (this.#resolve || this.#promises.length) { | |
const value = await this.#promises.shift() | |
if (value === undefined) { | |
break | |
} | |
yield value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment