I have a <select> tag that is populated and updated dynamically with <option> tags. Currently I let the MutationObserver change the local length variable that keeps track of the .length property of the <select>. The issue is that it seems to be some delay before the MutationObserver actually updates the value and oftentimes the variable is not the current length of the select list. Is there some workaround or is this the nature of MutationObserver?
Here's a demonstration of the behavior that you described. Now matter how many times I run it, the longest delta I see is always less than 1.5 ms. Is that what you mean by "delay"?
I wanted to write this as a comment initially, but there's no way to show a demo on-site in a comment, so I'm writing an answer. If you can refine your question to clarify or differentiate the issue, then I can potentially update this answer to address it (or delete it if it's no longer relevant to the new information).
<div>
<select>
<option>No options</option>
</select>
</div>
<script type="module">
const select = document.querySelector('select');
let {length} = select;
let previousTime = performance.now();
const observer = new MutationObserver((mutations) => {
for (const {addedNodes, removedNodes, type} of mutations) {
if (type !== 'childList') continue;
for (const node of addedNodes) {
if (node.tagName !== 'OPTION') continue;
length += 1;
}
for (const node of removedNodes) {
if (node.tagName !== 'OPTION') continue;
length -= 1;
}
}
const deltaMs = performance.now() - previousTime;
console.log('Observed', `length: ${length} (${deltaMs} ms)`);
});
observer.observe(select, {childList: true});
const setOptions = (items) => {
const options = items.map(str => {
const option = document.createElement('option');
option.textContent = str;
return option;
});
while (select.firstChild) select.firstChild.remove();
for (const option of options) select.appendChild(option);
previousTime = performance.now();
console.log('Set', `length: ${select.length}`);
};
const delay = (ms) => new Promise(res => setTimeout(res, ms));
setOptions(['a', 'b', 'c']);
await delay(2e3);
setOptions(['none']);
await delay(2e3);
setOptions(['one', 'two', 'three']);
await delay(2e3);
observer.disconnect();
</script>